- Home /
How do I allow my UI buttons to detect my "GameMaster" object after returning to the scene for OnClick events?
My game is structured like this:
The player enters the level select screen and picks a level
The player plays this level, beats it, and returns to the level select screen
When first entering my level select screen, there is a "GameMaster" game object that is responsible for actually changing levels. This object has been marked as "don't destroy on load," but the problem is that my UI buttons only detect it at the very beginning of my game because I manually dragged this object onto the buttons. After beating the level and returning to the level select screen my buttons don't work, as it says the "GameMaster" object is missing. How do I fix this? Is there a way to set the GameMaster onto the buttons every time I return to this scene? I very much appreciate any help you may be able to give me.
Answer by misher · May 07, 2018 at 07:07 AM
There is another GameMaster object created when entering the selectScreen second time. When you mark an object as DoNotDestroyOnLoad it will persist when loading other scenes, but when you turn back to the scene where it is created (select level scene) there will be created another copy of it. You can simply solve this by using singleton pattern. Here is a script: http://wiki.unity3d.com/index.php?title=Singleton. Make your GameMaster a singleton, so you can reference it using static field "Instance" from all other scripts. For example, your button should reference some other script dedicated for UI interactions (call it "SelectLevelUI" for example), this script will interact with GameMaster singleton and your buttons should reference the intermadiate script.