- Home /
Gameobject after destoryed still can be found.
Hi. I created a new unity project and made new simple script below. Once I hit play button in editor, in console window it shows "aaa" . Means unity still found the gameobject that I told it to destroy.
I am using 2018.1.4f1. any idea know whats happening?
void Start()
{
Destroy(GameObject.Find("aaa").gameObject);
Debug.Log(GameObject.Find("aaa").gameObject.name);
}
and even change code to below, debug still showing "aaa".
void Awake()
{
Destroy(GameObject.Find("aaa").gameObject);
}
void Start()
{
Debug.Log(GameObject.Find("aaa").gameObject.name);
}
It isn't destroyed until the end of the frame. Try waiting for a frame before looking again.
Thank you it works! but is there anyway to not use coroutine to solve this problem?
void Start()
{
StartCoroutine(waitThenGo());
}
IEnumerator waitThenGo()
{
Destroy(GameObject.Find("aaa").gameObject);
yield return new WaitForEndOfFrame();
Debug.Log(GameObject.Find("aaa").gameObject.name);
}
What is the problem? Why are you looking for something after you Destroy it anyway? If you are using GameObject.Find in an update method somewhere, then you need to change that it is should be used as little as possible, if at all.
Answer by fafase · Mar 21, 2019 at 04:40 PM
Destroy does not actually destroy the object but places it in a collection of object to be removed at the end of the frame (after Update). Since your Awake and Start are in the same frame, the object is still alive.
From the doc:
Actual object destruction is always delayed until after the current Update loop, but will always be done before rendering.
if you need to destroy something then use DestroyImmediately.
Many thanks to you ! This post relieves me of a full head-scratching day of coding and unfruitful debugging. You're my savior !
Answer by Nivbot · Mar 21, 2019 at 04:10 PM
I don’t need .gameObject at the end of either of those. You can also look in the hierarchy while it’s running an see if “aaa” is really there. I would think you’d get an error trying to log the name of a non-existent object
「you don’t need .gameObject at the end of either of those.」 good to know that thanks. :)
and Yes, like you said "aaa" is gone in hierarchy, and there is a error message in console window.
Your answer