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 :confused:

FYI: It is not firing the Debug.Log (collision.gameObject.tag); the IF statement is just a snipet

1 Answer

1

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.

No, that was the first thing I checked, those are set up fine. I also know it's set up fine for sure now, because: Update: After I created a whole new project the effect on other projects seemed to go away, not sure how or why though. It now appears to be unrelated to the mixer? Audio in new scenes also works fine and the script I use for audio settings also works fine in new scenes. It's probably a script that messes with audio settings going haywire. I'll give an update once I figure it out.