Problem with Collider2D

Hi every one ! I start with unity and today i have a problem, maybe simple for you :slight_smile:

private void OnTriggerEnter2D(Collider2D col )
{
if (col.tag == “EndPrefab”)
{
float x = col.transform.position.x;
float y = col.transform.position.y + 20;
float z = col.transform.position.z;

Destroy(col.gameObject);

go.GetComponent().position = new Vector3(x, y, z);
Instantiate(go);
}
}

col.gameObject is a child of a GameObject parent but the method Destroy(col.gameObject) is destroying my entire GameObject parent.

Someone can help me please ? :slight_smile:

It should only destroy the game object itself, not its parent. So do a quick check. Put thiese lines above the Destroy() method:

Debug.Log(col.gameObject.name, col.gameObject);
Debug.Break();

and then comment out the Destroy() method for test. You will see the name of the game object that you are destroying. It is probably where the unwanted behavior is happening. My guess is your parent game object has a collider2d too.

Let me know if it helped you.

1 Like

Milad is correct, your destroying your parent game object. Debugging helps track exactly where it goes wrong

1 Like