OnCollisionEnter2D finds no gameObject, then Unity crashes

I have a script with a OnCollisionEnter2D function. It seems to work fine most of the time. But every once in a while, an error occurs: the Collision2D object passed to the function does not have a gameObject member. This is unexpected, according to the Collision2D documentation.

I have structured my code to detect this condition, like so:

	void OnCollisionEnter2D( Collision2D coll ) {
		if ( coll.gameObject ) {
			//...do some stuff...
		} else {
			print( "Object " + name + " collided with a collider with no game object" );
		}
	}

Usually, Unity will hit this condition, then crash. I’m at a loss as to how to debug this, seeing as how Unity is crashing. Any ideas as to where to start? Thanks.

Looking at the snippet in your post, I think at first you should add a checking for the name or tag of the colliding object for example: if(coll.gameObject.name) as there’s a possibility that the object might collide with some other gameObjects having collider added to them.

That’s really strange! You could add a break point in your code (mono only) and step through the executing script and hopefully find the statement before Unity crashes. Which version of Unity are you using?

When you are printing the gameobject ‘name’ you should be using be coll.gameObject.name rather than name.

Please report this as a bug, thanks!