how to make the warning DontDestroyOnLoad only work for root GameObjects go away?
I keep getting this warning every time I try and use DontDestoyOnLoad:-
"DontDestroyOnLoad only work for root GameObjects or components on root GameObjects."
This didn't show up pre Unity 5.3 so whats up?
Is the object you're using it on the child of another object by any chance?
One of them was yes, I've had to split the game object into two parts now, one in the root with the script and the rest in the NGUI child object. The other 2 warnings are from the Prime31 plugins which I have no control over. This new behaviour is a right pain in the ass.
Thanks for the help though.
I get the same problem. it just starting happening with latest unity.
DontDestroyOnLoad only work for root GameObjects or components on root GameObjects.
Answer by masterton · Sep 26, 2017 at 06:10 PM
Unity calls this a warning but its more of an error because your child object WILL be destroyed on a scene switch. Add and call the function below instead. It goes up the parent chain and sets the DontDestroyOnLoad flag on the root object.
public static void DontDestroyChildOnLoad( GameObject child )
{
Transform parentTransform = child.transform;
// If this object doesn't have a parent then its the root transform.
while ( parentTransform.parent != null )
{
// Keep going up the chain.
parentTransform = parentTransform.parent;
}
GameObject.DontDestroyOnLoad(parentTransform.gameObject);
}
When I add it to a button in a canvas it makes everything in the canvas not be destroyed
You guys know about transform.root, right? Just call
DontDestroyOnLoad(transform.root.gameObject);
Answer by Salim · Jun 05, 2016 at 12:38 PM
I'm also having this error message when my NetworkManager object is a child in a parent object.
Simply putting it back to the root of the Hierarchy fixes it, but this is a problem if you want to organize your hierarchy with empty objects that act as folders.