A way to check if an object has DontDestroyOnLoad activated

Is there a way to check if a gameobject (or its parent) has been set to DontDestroyOnLoad?

Assuming that there’s no official way to query the property, I’ve come up with a workaround:

  1. Created a simple MonoBehaviour script that calls Object.DontDestroyOnLoad(gameObject) in Awake(), and named it DontDestroyOnLoad.
function Awake()
  1. Attached the script to all objects I don’t want to be destroyed, instead of doing the call from another component.

This way it’s modular and I can see and modify the property in the editor. And more importantly, I can query it like this:

var obj: GameObject;
if (obj.GetComponent.<DontDestroyOnLoad>()) {
   print("The object is kept between levels.");

unity has gameObject.scene for a while now

you can go all like

if (gameObject.scene.buildIndex == -1) //dontdestroy activated


You can now use gameObject.scene.name == "DontDestroyOnLoad" to check if a scene is flagged with DontDestroyOnLoad.

Note that the above answer of checking gameObject.scene.buildIndex will return -1 for addressable, assetbundle in additional to DontDesroyOnLoad scene, and it likely isn’t what you want.

We worked around this function call with HideFlags. Worked for us.
I guess HideFlags.DontSave is almost the same as DontDestroyOnLoad().

gameObject.hideFlags = HideFlags.DontSave;

if (!((gameObject.hideFlags & HideFlags.DontSave) == HideFlags.DontSave)) {
  // You may be destroyed.

DontSave means that the object is not saved to the scene. Further if you load another scene this object does not get destroyed, because it is not part of the scene. Just in case you’re wondering why ‘dont save’ even you want to ‘dont destroy’ it.

Ouh and you could also display a enum popup in the inspector to define what flag should be assigned. More common approach?!