- Home /
How can I change my script to destroy a GameObject on hit?
I'm making a FPS game, and when I shoot something, it just knocks it back. This was my original idea, however, I now want it to destroy a game object when it is shot. Here is my script:
var projectile : Rigidbody;
var speed = 10;
function Update () {
if ( Input.GetButton ("Fire1")) {
clone = Instantiate(projectile, transform.position, transform.rotation);
clone.velocity = transform.TransformDirection( Vector3 (0, 0, speed));
Destroy (clone.gameObject, 5);
}}
Answer by zBlanco · Apr 02, 2013 at 12:03 AM
You could get the object that is hit by the projectile using the OnCollisionEnter function from a script attached to the projectile and simply use the Destroy function.
So for example(Script attached to projectile):
function OnCollisionEnter(other: Collider){
if(other.tag == "(tag used for gameObject)"){
Destroy(other.gameObject);
}
}
Thanks for you help, mate. One more problem. I'm getting the following error: "Script Error : OnCollisionEnter" "This $$anonymous$$essage Parameter must be of type: Collision" "This message will be ignored." Any solutions?
i tried to use this script but it is not working. Is it suppose to destroy the object it hits or the object the script is attached to? You are not making that clear.
Answer by Ekta-Mehta-D · Oct 04, 2013 at 07:25 AM
You can use this code :
function OnCollisionEnter(collision : Collision)
{
if(collision.gameObject.tag == "zombie")
{
Destroy(gameObject); // destroy the object to which script is attached
Destroy(collision.gameObject); // destroy the other collided object
}
}
You can attach this script with projectile..
This code will work.. Njoy..
Your answer

Follow this Question
Related Questions
Gun Shooting Animation Won't Play 0 Answers
fps shooting enemy 1 Answer
Shooting script problem. 2 Answers
Gun reload and clip size 0 Answers