- Home /
Game doesn't destroy objects in order?
So I've made a script where if an object with a certain tag hits the collider, it gets destroyed. There are multiple objects with this tag. The problem is when an object hits this collider, another object gets destroyed with that tag.
How can I make it that when the object that hits the collider gets destroyed and not another object with the same tag?
void OnTriggerEnter2D(Collider2D collider) {
death = true;
Score.AddPoint ();
Destroy (GameObject.FindWithTag ("coin"));
}
Answer by Xarbrough · Jan 09, 2016 at 10:31 PM
// This is triggered on e.g. a player MonoBehaviour
void OnTriggerEnter2D(Collider2D other)
{
// when the trigger we are colliding wih has a "coin" tag
if (other.CompareTag("coin"))
{
// then destroy the coin
Destroy(other.gameObject);
// and add a point to the score
Score.Addpoint();
}
}
// Or put this on the coin
void OnTriggerEnter2D(Collider2D other)
{
// When the other collider is tagged with player
if (other.CompareTag("Player"))
{
Player player = other.GetComponent<Player>();
// and we actually find a reference to its MonoBehaviour
if(player != null)
{
// Add a point to the player
player.AddPoint();
// And destroy this.
Destroy(this.gameObject);
}
}
}
Your answer
Follow this Question
Related Questions
Hi! How can I use the OnTriggerEnter2D function for the game objects that I instantiate? 3 Answers
Detecting and setting active a child object using VRTK 0 Answers
OnMouseOver with 2 overlapping object not working properly 0 Answers
How to make the bodyParts to follow same places and directions as the player? 0 Answers
How to check if object are link via other collider 0 Answers