- Home /
Problems with GameManagers
So in my Game I have a GameManager, which is set to DontDestroyOnLoad. The GameManager mainly consists of delegates and events, also variables. Every scene in my game has UI buttons which activate the events of my GameManager with OnClick(). Whenever I restart my scene or change to another, all those UI buttons lose the reference to the GameManagerScript. What should I do, so that the UI buttons don't lose reference to the GameManager?
Answer by isbdnt · Jul 05, 2017 at 01:39 AM
dont use DontDestroyOnLoad
why not? This is exactly when to use it. You can make it even better by using this and a singleton like design pattern for the game manager. That way Your UI elements can search for the game manager when the scene loads and they will be sure to find the one, true Game$$anonymous$$anager.
Answer by Cornelis-de-Jager · Jul 05, 2017 at 02:42 AM
Maybe try adding DoNotDestroyOnLoad to your UI as well?
Answer by Jwizard93 · Jul 05, 2017 at 11:50 PM
Make a GameManager Prefab. Make sure it has Don't destroy on load. Make sure it has a unique tag.
Add functionality in Awake() such that it searches for any active GameObject with the GameManager Tag. If it doesn't find anything then perfect. If it does find something then have this GameManager destroy itself. It isn't the real GameManager.
Drop that prefab in every scene. Now no matter what level you startup there will be a GameManager. If you move from one scene to the next the new GameManager will detect the existence of the first game manager and destroy itself.
When the scene loads just have that scene's UI search out the GameManager by its tag.
Do that in the UI element's Start() function that way you know Awake() was already called on the GameManager and there will be only one to find.
$$anonymous$$ight have to tweak this logic a bit to make sure the real Game$$anonymous$$anager doesn't destroy itself. I'm sure you will figure it out.