- Home /
Instantiated object that has a collision is not firing OnCollisionEnter2D
I have objects: a wall and a player that shoots "something".
Both are prefabs and are loaded dynamically like this:
Transform bulletClone = GameObject.Instantiate (shootTile, playerPos, Quaternion.identity) as Transform;
Instantiate (Wall, new Vector3 (x, y), Quaternion.identity);
They actually collide, but they do not trigger my following function:
void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log (collision.gameObject.tag);
if(collision.gameObject.name == "enemy"){
Destroy(this.gameObject);
}
}
I have a rigidBody2D on the bullet, with a Box Collider 2d. On the wall I also have Box Collider 2D.
My player has both a ridigBody2D and a BoxCollider2D, and that is triggering on the bullet AND the wall. But for some reason it is not triggering for my instantiated objects :/
FYI: It is not firing the Debug.Log (collision.gameObject.tag);
the IF statement is just a snipet
Answer by tanoshimi · Oct 09, 2016 at 06:35 AM
You're testing for a collision only with an object named "enemy", but I don't see you assign that name to the instantiated object anywhere. So you need something like:
Transform bulletClone = GameObject.Instantiate (shootTile, playerPos, Quaternion.identity) as Transform;
bulletClone.name = "enemy";
Either that, or test for collisions based on the tag of the object, which the instantiated object will inherit from its prefab.
The IF statement is just a snipet. The Debug.Log (collision.gameObject.tag);
is simply not firing, and that should fire.
Your answer
Follow this Question
Related Questions
Help On Checking OverLaping in instantiating 0 Answers
Projectiles trigger affecting other projectiles of same prefab - C# 0 Answers
Object created through Instantiate does not update its position at the first frame 1 Answer
Animation doesn't affect the new instantiated object. 0 Answers
Why is it important to create an empty gameobject for my prefabs? 0 Answers