Search Unity

Problem with Collider2D

Discussion in '2D' started by giinsen, Oct 13, 2017.

  1. giinsen

    giinsen

    Joined:
    Oct 13, 2017
    Posts:
    4
    Hi every one ! I start with unity and today i have a problem, maybe simple for you :)

    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<Transform>().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 ? :)
     
  2. MiladZarrin1

    MiladZarrin1

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

    Code (CSharp):
    1. Debug.Log(col.gameObject.name, col.gameObject);
    2. 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.
     
    MurcsRoyce likes this.
  3. MurcsRoyce

    MurcsRoyce

    Joined:
    Jul 19, 2017
    Posts:
    38
    Milad is correct, your destroying your parent game object. Debugging helps track exactly where it goes wrong
     
    MiladZarrin1 likes this.