- Home /
Undo DontDestroyOnLoad?
Is there a way to reverse DontDestroyOnLoad? I'd like my character controller to persist across scenes, but that character controller might get switched to a new body during play, and the old body would no longer need to persist. I guess I could keep track of bodies and destroy unoccupied ones via script when a new scene is loaded, but it would be cleaner if I could just turn off "DontDestroyOnLoad" when the body is no longer being occupied.
Answer by Alverik · Aug 28, 2018 at 02:06 AM
DontDestroyOnLoad() simply moves an object to the special Scene "DontDestroyOnLoad", so all you need to do is move it back to the active scene:
SceneManager.MoveGameObjectToScene(TargetGo, SceneManager.GetActiveScene());
Answer by Bunny83 · Apr 09, 2018 at 03:19 AM
Currently there is no way (i know) to revert the DontDestroyOnLoad mark of an object. However you could simply parent the object to an empty gameobject. DontDestroyOnLoad only has an effect on root objects.
private static Transform m_DestroyOnLoadGO;
public static void DestroyOnLoad(GameObject aGO)
{
if (m_DestroyOnLoadGO == null)
m_DestroyOnLoadGO = (new GameObject("DestroyOnLoad")).transform;
aGO.parent = m_DestroyOnLoadGO;
}