DontDestroyOnLoad: Many instances of one object

In my game I have many levels: main level (street) and other levels (houses).
Player can come to the houses from the street and when he came back to the street, I want to place him near that house, which he has entered.

But now, when I load street level, player every time stays at the same place. I know that each time when load new scene, all objects from the old scene are destroys. And I can prevent it by using DontDestroyOnLoad() function on the player object. But then each time when I load main scene, I have new instance of player object, so I have more than one player on the scene at once.

How can I solve it? It should be easy way because it is basic mechanism for many games.

What you’re looking for is called a Singleton system. It’s a setup that allows only one of a specific object. There’s a few ways to do it, this is how I make mine:

public static ClassNameHere instance;

void Awake()
{
     if(instance == null)
     {
          instance = this;
          DontDestroyOnLoad(gameObject);
     }else if(instance != this)
     {
          Destroy(gameObject);
     }
}
  1. Create an application variable in Visual Scripting script (or global variable if you use C#) : type = List , name = “Dont Destroy On Load”
  2. On Start > Check Loop of all items in List “Dont Destroy On Load” has any items = GameObject.Get Name >
    if Yes : Destroy This.GameObject , No : Add GameObject.Get Name to List “Dont Destroy On Load” & Add event this.GameObject.DontDestroyOnLoad > Done
  • You can do it in 1 second only in Visual Scripting ( I don’t know how to code it in C# , sorry :smiley: ) , get the script free on my channel : Unity No Code | Leo N , at video “Unity Ads tutorial”