- Home /
C# - How to stop unity destroying custom objects on exiting playmode?
I'm using [ExecuteInEditMode] to run my script in the editor - the script works fine and creates some objects from a custom class that I've written.
I was surprised to discover that all of my custom objects are destroyed when entering or exiting playmode leading to problems for me with null references in my script.
Is there any way to prevent objects being destroyed when entering or exiting playmode? Unity seems to flush everything from memory. My custom class derives from ScriptableObject but using DontDestroyOnLoad(this) doesn't seem to make any difference.
Answer by _Amael_ · Aug 30, 2012 at 11:29 PM
Answering my own question here as the cause to this problem was human error!
I forgot to put [System.Serializable] before one of my custom class declarations (I can only blame late night sleep deprived coding) and now that it's been added, Unity is holding onto all the data that I need.
Answer by dNSavar · Aug 29, 2012 at 06:06 PM
I am not sure if it will help you but you can detect when your are exiting playmode with this:
public void OnApplicationQuit() { if (Application.isEditor) IsEditorStopping = true;
}
Also, when you want to use DontDestroyOnLoad, don`t use the script, use the object like this: DontDestroyOnLoad(this.gameObject)
$$anonymous$$any thanks for the suggestions - I looked into using these, amongst many other thing, while trying to fix my problem.
Turns out I forgot to put [System.Serializable] before one of my custom class declarations (I'd remembered to put it on all but one of my classes) and now that it's there, I'm happy to report that Unity is no longer destroying everything on enter/exit playmode :)