What is the appropriate way to destroy an object in OnTriggerEnter?

Here’s my current code:

void OnTriggerEnter(Collider collider)
{
	Debug.Log("Collision");
	if (collider.transform.gameObject != parent)
	{
		Debug.Log("EnemyCollision");
		Destroy(transform.gameObject);
		CreateExplosion();
	}
}

I also tried the following:

void OnTriggerEnter(Collider collider)
{
	Debug.Log("Collision");
	if (collider.transform.gameObject != parent)
	{
		Debug.Log("EnemyCollision");
		Destroy(transform.gameObject, 1);
		CreateExplosion();
	}
}

Both of these methods throw an error, but they seem to work correctly. The error is:

Destroying object immediately is not permitted during physics trigger and contact callbacks. You must use Destroy instead.
UnityEngine.Object:DestroyImmediate(Object)

What is the correct way to destroy an object inside of an CollisionEvent?

This should happen, but I can only provide you the script in JavaScript. I apologize.

var objectToBeDestroyed : GameObject;
function OnTriggerEnter(collider : Collider){
//place your logic here
Destroy(objectToBeDestroyed);
}

This is working fine for me. Convert this to C#.

I’ve encountered the same problem. Fixed it by calling a coroutine with one “yield return null” before the Destroy. So you’re waiting to get out of the physics step and back into regular game update before calling the destroy.

It’s a bit messy but seems to do the trick.