- Home /
How to destroy a gameobject on collision
I have a fps shooter game and my shooter shoots glass ballish things and the enemys are zombies, but the problem is I need to know how to destroy them when the ball hits them. I know its a OnCollisionDestroy, script but I don't know how to write one so it works.Please Help.
Answer by nSwarm · Apr 28, 2012 at 02:15 AM
The OnCollisionEnter function of a GameObject is called whenever another collider hits your GameObject, as long as one of them has a rigidbody.
What you need to do is create a script on either your projectile or the zombie that contains the OnCollisionEnter function (make sure you declare it exactly like they do in the docs.) Then call the Destroy() function on the appropriate object.
This example would be within a script on the projectile:
// Note: untested C# code
private void OnCollisionEnter(Collision collision)
{
// You probably want a check here to make sure you're hitting a zombie
// Note that this is not the best method for doing so.
if ( collision.gameObject.name == "zombie" )
{
Destroy(collision.gameObject);
}
}
Reference This may likely be of some help as well. http://unity3d.com/support/documentation/ScriptReference/Collider.OnCollisionEnter.html
You can read more about various collider combinations (what will and will not call these scripts) here: http://unity3d.com/support/documentation/Components/class-MeshCollider.html
Hope this helps!
Answer by KingDeveloper47 · Jun 12, 2017 at 08:45 AM
public GameObject Circle; public void oncollision(Collision col ){
if (col.gameObject.name == "Circle")
Destroy (this.gameObject);
Debug.Log ("Destroyed");
}
It does not work .How to solve this problem