0
\$\begingroup\$

I have this simple code, but it does not prevent the object it's attached to from being destroyed on load:

 void Start()
{
    DontDestroyOnLoad(gameObject);
    Debug.Log(gameObject.scene.name);
}

It also shows this Warning:

DontDestroyOnLoad only works for root GameObjects or components on root GameObjects.
UnityEngine.StackTraceUtility:ExtractStackTrace ()
wfb:Start () (at Assets/Script/wfb.cs:9)

DontDestroyOnLoad(gameObject); is on line 9.

\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

Check your Hierarchy to see if the object is the top-level parent or a child of another object.

If the game object is a child, the DontDestroyOnLoad() function will not work.

In order to not destroy the game object you need to place it at the root level of the scene, not parented to any other object, so that the game object will persist to the other scene.

The warning is saying that this object is currently a child (or grandchild, etc.) of another root object in the scene.

\$\endgroup\$
0
\$\begingroup\$

set this line code before DontDestroyOnLoad you will avoid the error: yourObj.parent = null;

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .