Smile3329
Smile3329

Reputation: 19

Unity Transform GetChild() works weird

I have 4 objects but when i deleting GameObject in transform.GetChild(n) deleted object still alive.

Before deleting

After deleting

Logs

IEnumerator DeletePlanet(int item) {
    yield return new WaitForSeconds(5);
    planets.RemoveAt(item);
    Destroy(transform.GetChild(item).gameObject);
    for (int i = 0; i < planets.Count; i++) {
        UpdatePositions(transform.GetChild(i).gameObject.GetComponent<RectTransform>(), i);
    }
    
    for (int i = 0; i < startPlanetCount; i++) {
        print(transform.GetChild(i).gameObject.GetComponent<RectTransform>().anchoredPosition);
    }
}

Idk what can i do here.

Upvotes: 0

Views: 556

Answers (1)

CrippledTable
CrippledTable

Reputation: 816

There could be two things going on here.

  1. The script is removing the item from the parents transform before deleting it, so the object is no longer accessible using transform.GetChild

  2. The script assumes that a destroyed object is instantly destroyed, but it is not. In an update method, the object is destroyed after the update method is finished. I'm not sure when an object is destroyed during a coroutine, but my guess is after the coroutines finishes or after a yield.

Upvotes: 1

Related Questions