Find objects with DontDestroyOnLoad

Here’s a curiosity - how would you find all gO in the scene where DontDestroyOnLoad() has been called upon them?

Obviously you can make a flag or whatever yourself, but I’m asking if it is fundamentally knowable in the Unity engine?

The saved objects are handled on the native side, and there is no way I know of to hook into that side of Unity.


As an aside, here’s an example of using an extension to track such a quality:

I would create a an extension for Object which stores all saved objects, something like this:

public static class ObjectExtension {

	private static List<Object> savedObjects = new List<Object>();
	
	public static void DontDestroyOnLoad(this Object obj){
		savedObjects.Add(obj);
		Object.DontDestroyOnLoad(obj);
	}
	
	public static void Destory(this Object obj){
		savedObjects.Remove(obj);
		Destory(obj);
	}
	
	public static List<Objects> GetSavedObjects(){ 
        return new List<Objects>(savedObjects); 
    }
}

Now, to save the object you’ll have to use this.DontDestroyOnLoad(); instead of the normal DontDestroyOnLoad(this);

EDIT:

I started looking into this and found that setting a GameObject’s hideflags to HideFlags.DontSave means (as far as I can tell) the same thing as DontDestroyOnLoad, except that none of Unity’s functions (Update, etc.) are called. The one with hideflags might also leak if not destroyed manually…

Finding GameObjects with its hideFlags set to DontSave is trivial.