Destroying Object OnTriggerEnter2D not working
Hello guys,
I have trying to resolve this problem for a very long time and I seriously can't figure out what to do to fix this. I have the below code on a object with a Box Collider 2D set to Trigger:
public Object CollectableDestroyedEffect;
public Object BallDiesEffect;
public Object EnemyDestroyedEffect;
private string objectTag;
void OnTriggerEnter2D(Collider2D other)
{
objectTag = other.gameObject.tag;
switch (objectTag)
{
case "Enemy":
other.GetComponent<EnemyCollisions>().DestroyEnemy(true, false);
break;
case "Collectable":
Instantiate(CollectableDestroyedEffect, other.transform.position, Quaternion.identity);
Destroy(other);
break;
case "Ball":
//Destroy(other);
Instantiate(BallDiesEffect, other.transform.position, Quaternion.identity);
GameManager.instance.SpawnBall();
break;
case "Projectile":
Instantiate(EnemyDestroyedEffect, other.transform.position, Quaternion.identity);
Destroy(other);
break;
//default:
// Instantiate(CollectableDestroyedEffect, other.transform.position, Quaternion.identity);
// Destroy(other);
// break;
}
}
What I am having problem with is the tag "Collectable".
I made sure the tag is correct, I made sure all of the objects have a RigidBody2D, and I made sure that they are on the same plane and same layer. The weird thing is that the effects are instantiated correctly (so the Instantiate code) runs and I can see, thing is, the objects are getting destroyed at all.
Worthy of note is that the Collectable tagged objects have Box Collider 2D and set to trigger.
Any idea how I can fix this?
Answer by Kurtisi · Apr 03, 2016 at 09:03 AM
Well as i understand you want to destroy collectable after instantiating some effect when you enter it's trigger zone..
Have you tried managing this in several if statements?
if(other.tag=="Collectable")
{
Instantiate(CollectableDestroyedEffect, other.transform.position, Quaternion.identity);
Destroy (other.gameObject); //or Destroy(other);
}
Well that actually fixed it!
other.gameObject was what I am missing ins$$anonymous$$d of other only. I don't understand it much, but I am guessing if I do Destroy(other) only, I am only destroying the collider (as other is of type Collider2D and not gameObject)?
I didn't change it into an if statement though, any reason why I would use if statements ins$$anonymous$$d of a Switch? Just curious that is all.
Thanks a lot $$anonymous$$urtisi, you are awesome!
Yes, that is exactly the reason because you destroy collider only.
I suggested if statements just because it's easier for me like that way :P
Your answer
Follow this Question
Related Questions
Remove Door's collider if cube is in the trigger,Destroy Door's Collider if box is in the trigger 0 Answers
Destroy instatiate object on trigger enter / collision,destroy instantiate prefab on trigger enter 0 Answers
C# OnTriggerEnter Issue 3 Answers
OnTriggerExit2D doesn't work when one of gameObject setActive false. 0 Answers