How to check if GameObject exists in hierarchy (is instantiated)
How do I check this? Is there a way to do this? It may seems like a dumb question (it may be) but when working with prefabs nothing works, activeInHierarchy, the GameObject bool operator, nothing works because in fact the object exists because of the prefab, checking those will return true but they are not strict to the scene hierarchy, it can be "active in hierarchy" but not on the scene...
Answer by Rodolfo-Rubens · May 01, 2017 at 05:03 PM
It seems like I need to null the reference to the object that I'm checking if it exists, even when the object gets destroyed because you can still access the object after it gets destroyed and if I null check it it will return false (in the inspector it will show as Missing, the reference is not null which is pseudo not destroyed in this case, but I destroyed it so I want it to be null), so I needed to make sure the reference is manually nulled after the object got destroyed.
BTW, this weirdness only happens in the same frame that the object gets destroyed, need to wait a frame before null comparing the object, if you wait you will not get not null for the object destroyed. This is needed for OnDestroy do its thing.
Checking if objects are active and spawned in the Hierarchy (if you have a field that can contains prefabs and spawned objects) I don't know if this is possible.
I just stumbled onto this again: https://forum.unity3d.com/threads/object-null-returning-true-but-object-doesnt-exist-anymore.468762/
Answer by Denvery · Sep 29, 2015 at 10:39 AM
As a way, you can assing specific tag to you prefab, then call GameObject.FindWithTag("YourTag")
. This function will return one active GameObject with this tag, if exist
This is not viable for me because there may be a lot of GOs with the same tag n the scene... Thanks for replying.
You can call FindObjectsWithTag. It will find all active objects with this tag
Answer by Sickwitit · Sep 29, 2015 at 02:23 PM
Like this? You could also change the string parameter to GameObject and change the if condition accordingly.
public bool IsChildAliveInParent(Transform parent, string childToCheck)
{
bool isChildAlive = false;
for(int i = 0; i < parent.childCount; i++)
{
if(parent.GetChild(i).Equals(childToCheck))
{
isChildAlive = true;
break;
}
}
return isChildAlive;
}
This is a good solution, although, my object is in the root so my parent will be null...
Your answer
Follow this Question
Related Questions
Game Object disappear after move to another Scene 0 Answers
Object not visible in Scene tab until double click it on the Hierarchy. 1 Answer
win game & loos game 0 Answers
Help me! Create a game object falling from the top scene at click mouse point! T________T 0 Answers
Unity removes all objects includes the main camera in Hierarchy when i start test play 2 Answers