Asimm Asimm - 3 months ago 17
C# Question

Save object between scenes using DontDestroyOnLoad Unity C#

I'm making a 2D game where my character can go in and back out from different rooms, so since every room is a different scene I need to be able to somehow keep my character throughout every single scene, for that purpose unity offers DontDestroyOnLoad()
So I did use that function whenever I'm switching my scenes, however there is a problem with that.

Let's assume that my rooms are only 2 and they are really simple looking like this

enter image description here

Here in this scheme the main room is the one that you start your game in, it contains already spawned prefab of the character. Once we go to the second room my character is being saved with all his good stuff, however if we go back to the main scene/room we can now see 2 characters. Why ? Because our initial character is not being destroyed when different scene are loaded and we also have one that is being created along with the Main room/scene. Now this is really nasty and I don't know how to fix that, I also have the same problem with some scripts that I need throughout every single scene. Any help is appreciated.

Answer

The normal solution is you don't create objects that are set to DontDestroyOnLoad in scenes that can be viewed more than once.

What most people do is create a pre-load scene that is the very first scene that loads with the game that creates all objects that survive between scenes, then that pre-load scene loads the "Main game scene".

If you don't want a pre-load scene then your game object needs to check on on Awake if another instance of the game object already exists. If it does find a instance then it needs to destroy itself. The first instance won't find any other instances so it won't be destroyed but all future instances will be.