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?
dont use DontDestroyOnLoad
Maybe try adding DoNotDestroyOnLoad to your UI as well?
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.