- Home /
Destroying objects
For my game I will have to use Instantiate to spawn a lot of the same object (Carrot). My main character has a script attached which tells it to destroy that object (Carrot)but when I drag the object (Carrot) I want to destroy into the inspector it only destroys that specific object (Carrot). Is there a way to make it only destroy the object it comes in contact with?
Answer by LCStark · Oct 02, 2018 at 08:14 AM
You'll have to use colliders to detect when your objects come in contact with one another. You can use tags to determine what object you've collided with and whether to destroy it or not. Check out the Unity tutorials: https://unity3d.com/learn/tutorials/. The Space Shooter tutorial and the 2D UFO tutorial have easily accessible information on collisions.
Alternatively, check out the Unity Manual page on colliders: https://docs.unity3d.com/Manual/CollidersOverview.html.
I am using colliders to detect whether the objects come in contact with each other or not and the collision itself is working fine. The problem is that I want to destroy the carrot (which does not have a script) via the main character (who does have a script). Using tags won't work as it will destroy all the object with that tag.
When you check for collisions, your collision function (OnCollisonEnter, OnTriggerEnter, etc.) has a collision
or collider
parameter. In it there's a reference stored to the object you are colliding with. You can check that object's tag (collider.tag
or collision.collider.tag
) and if you deter$$anonymous$$e that it is a Carrot
, you can destroy only that single object by using Destroy(collision.collider.gameObject);
or Destroy(collider.gameObject);
.