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);
}
}