Reputation: 7294
Note: I have many years of development experience, but I'm a total beginner in Unity.
I was wondering what is the best practice for managing your GameObjects across scenes?
As you may know, each Scene has an Hierarchy tree with actual instances, lets say that I have a ScoreManager game object that I want to instantiate only one time, but I want to avoid the singleton pattern. (As it's a bad practice). Let's also say that the ScoreManager requires an instance of LevelsManager and so on...
One solution that I'm familiar with is Dependency Injection, but I did find any tutorial that uses it. All the tutorials that I see instantiate GameObjects in the Hierarchy tree, links other GameObjects via a public propery... which can count as a way to do Dependency Injection, but only for the current scene...
So, do you have a good practice that you use and love?
Thanks!
Edit:
@Shogunivar suggested DontDestroyOnLoad, the problem with that is that you should put only one GameObject in the first scene hierarchy, for example WelcomeScene, it will persist in all the future scene that were loaded.
The problem with that is that you might want to test (Press Play) say on Level01Scene that requires this GameObject to exist, but it's not there, you must first load the WelcomeScene that has this GameObject in the Heirarchy.
Putting the same GameObject also on Level01Scene will cause it to get duplicated, and will never destroy...
To solve this duplication, the only solution (That I know of) is to use Singleton. It's not "the-end-of-the-world", but this is the purpose of this question. Any other best-practice to handle this issue (In Unity)?
Upvotes: 2
Views: 502
Reputation: 34
Zenject is really powerful. There is some great documentation on their Github page as well that explains a lot. This is a great way to manage global bindings.
However, if you want something far simpler, you could inherit from a singleton class. Most people will advise against it, but it does work and it is super easy.
public class SingletonController : MonoBehaviour {
public static SingletonController Instance;
private void Awake() {
if (Instance != null) {
Destroy(gameObject);
} else {
Instance = this;
}
}
}
Upvotes: 1