How can I make my instance of the Singleton MonoBehaviour class start as new when the scene reloads?

I have a SingletonManager class with an instance of Singleton (and an interface to it). GameObject 'LevelManager' does not have to be stable throughout the entire application life cycle and should be replaced with a new instance each time a new level is loaded.

When I run my current code, when the scene loads a second time, the "LevelManager" seems to be missing, even though the GameObject (with the script application) is in the scene. I understand that this is probably because I'm still trying to access the old link.

What is the best way to ensure that my "SingletonManager" stores a new instance of "LevelManager" every time a new level is loaded?

My code (inappropriately deleted):

SingletonManager:

public class SingletonManager { private static LevelManager instance; public static ILevelManager Instance { get { if (this.levelManager == null) { this.levelManager = GameObject.FindObjectOfType(typeof(LevelManager)) as LevelManager; } return this.levelManager; } } } 

Singleton is not permanent:

 public class Singleton<Instance> : MonoBehaviour where Instance : Singleton<Instance> { public static Instance instance; public bool isPersistant; public virtual void Awake() { if(isPersistant) { if(!instance) { instance = this as Instance; } else { DestroyObject(gameObject); } DontDestroyOnLoad(gameObject); } else { instance = this as Instance; } } } 
+4
source share
2 answers

What I understand from your question: you need a new object, since the game stage is changing ,
If I understand correctly, this can help you.
Try Multiton pattern for your solution.
here is an example

 class levelManager { private static readonly Dictionary<object, levelManager> _instances = new Dictionary<object, levelManager>(); private levelManager() { } public static levelManager GetInstance(object key) { // unique key for your stage lock (_instances) { levelManager instance; if (!_instances.TryGetValue(key, out instance)) { instance = new levelManager(); _instances.Add(key, instance); } return instance; } } } 

Note. “I'm just giving you an example of not perfect code for your class .”
Link: http://en.wikipedia.org/wiki/Multiton_pattern

+1
source

A simple solution:

Create a manager for level managers. It should be stable and have an array of ready-made LevelManager files (I assume that you are creating them from the collection?). When each level is loaded, ask him to create the appropriate LevelManager collector (or create it or something else that is necessary to create it).

Each level manager should simply install an instance in Awake and let the level destroy it at the end. (i.e. your fickle singleton.)

 public class LevelManagerSpawner { public GameObject[] LevelManagerPrefabs; void OnLevelWasLoaded( int levelNumber ) { Instantiate( LevelManagerPrefabs[ levelNumber ] ); } } 
0
source

Source: https://habr.com/ru/post/1502603/


All Articles