I have created a menu on Unity using the built in UI components,I can't create this on a seperate scene because I used the toggle button, which basically when you click it, it spawns a specific object (I have 4 of these toggle buttons). I have completed making the menu on the my current scene. My problem is that when I start on runtime, the menu appears in front of the first person character controller, and when I move the mouse to click the toggle, the camera controller follows the mouse movement. How do I fix this? Also when I click all of the toggle buttons, I want the UI to dissapear, so it isn't shown when I am playing the game because atm when I click the toggle buttons, the actual buttons stay on the screen whilst I am navigating around the scene, is there any way to make this invisible?
I solved this problem in several different games with the state machine approach.
Your game has at least two different UI states in which it reacts differently to user input:
- the "in menu" state
- the "playing in first person" state.
It might have even more states you didn't mention or aren't aware yet that you will need them. For example what almost every game needs once in a while is a null-state in which most input is ignored.
Implement each of these different input-states as a separate MonoBehaviour.
Create another script
InputStateManager which references all input-states in the scene and provides methods to switch between them. Such a state switch is performed by setting
enabled = true on the state you request and
enabled = false on all others. The
OnDisable methods of your input states can also take care of activating and deactivating any UI objects which should only be visible while in that state (like the canvas of your menu).
The advantage of this method is that you achieve loose coupling between your different input states and can easily add a new one without touching the code of the existing ones.
I'll tell you what I did.
I had a
bool on a camera scripts that says whether the camera should rotate or not, so I called it
bool shouldRotateCamera = true;
And when you pop the menu, whether it's by using Esc or any other way, you can change that value in camera script to
this.shouldRotateCamera = false;
In the update method of camera script always check
if (shouldRotate). The camera should rotate if so.
Regarding the UI, you can technically enable/disable it.
If there are any questions, feel free to ask.