Problem with "DontDestroyOnLoad" (it creates like a new scene)

Hello !

I’m developping my 2nd game on Unity !
I’m following a tutorial on Youtube, but i have a problem with the “DontDestroyOnLoad” function.

When i start the game, i have a new scene like that :

That’s a bit embarassing, i can’t acces to some data in my Scene called “1”.

Could someone help me please ?

I’m really not sure what you mean. What are you trying to access? This is just how Unity displays DontDestroyOnLoad objects. They are still in the scene.

That’s not just how it’s displayed, that’s how DontDestroyOnLoad works. It moves it to the DontDestroyOnLoad scene so when the “1” scene is unloaded, the objects in DontDestroyOnLoad aren’t destroyed.

As to the actual problem here, why can’t they access the objects in the “1” scene? Scenes are just collections of objects, they can interact just fine. Scripts can find, interact with objects in other scenes, physics objects work fine between scenes, etc. So what exactly isn’t working?

I was trying, in my scene “2”, to access to the Canvas in the scene “2”, and I couldn’t find it :confused:

I was using “OnLevelWasLoaded” to find the Canvas and use it on my character (who was spawning thanks to “DontDestroyOnLoad”).

It was not working …

I spent 5 hours on it, I gave up and i’m not using “DontDestroyOnLoad” on my Character anymore…

If someone have an idea, i can try it again.

Thank you for your answers :slight_smile:

Yeah, my idea is, don’t use DontDestroyOnLoad on your main character. You changed it now, but I’m not sure why you wouldn’t just spawn him in the new scene anyway.

When you change scenes all references to objects from the current scene are obviously lost. If your character ‘knows’ the Canvas from scene 1 and you change scenes, that reference will then be empty. It’s just the way it is.
Why OnLevelWasLoaded (which is deprecated by the way) doesn’t work I don’t know without seeing your project. Probably some execution order problem?

Of course there are solutions to this problem, but I’d still advise you to just not use DontDestroyOnLoad on a dynamic object like the main character. Use it on Managers for sound, UI, game logic or stuff like that.
Anyway, what you could do if you must:

  • Register the Canvas with the Player object on its creation (have a method RegisterCanvas(Canvas c) in the Player script and in the Awake() or Start() method of the Canvas call that method with itself
  • Check if the canvas is referenced in the player object (if canvas.gameObject != null) before you do anything with it. If it isn’t, FindObjectOfType()
  • Is there a problem with making the Canvas DontDestroyOnLoad() as well? Then you could just reference it.

I can think of more, but as I said - I don’t know your game, so I don’t know how important having the character not destroyed is.