- Home /
Open and close UI Menu on background mouse click
Hello all
I am trying to make a point and click game in unity 5.2.2.
My problem is that I need to have a UI menu to open, when the player clicks with the left mouse button on the background sprite, and it should close again, when he click on it again. I have created a script, and so far it works like that, but It also closes, when I click on the menu buttons itself, which means that I can't use the menu which opens. Please help me to how I can achive that.
The way the menu should work, is like in the game Game Dev Tycoon, where the player can open and close the menu, when clicking on the game background.
Here is my script, in its current form.
using UnityEngine;
using System.Collections;
/// <summary>
/// This is the main class, for the entire game. The purpose of this class, is to control any gameplay in the game.
/// </summary>
public class GameManagerScript : MonoBehaviour {
public GameObject gameUI; //The actual Game UI
public void Awake()
{
gameUI.SetActive(false);
}
// Game Manager Game Loop
public void Update()
{
CheckForKeyInput();
}
void CheckForKeyInput()
{
//Mouse0 = First mouse button
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Debug.Log("Mouse0 button fired!");
gameUI.SetActive(!gameUI.activeSelf);
}
//If escape, exit the game
else if (Input.GetKeyDown(KeyCode.Escape))
{
Debug.Log("Application has been exited");
Application.Quit();
}
}
}
Answer by DeathDev · Nov 07, 2015 at 07:29 PM
You seem to be checking for mouse input, not mouse input on that specific object.
If you add a box collider2D to that object(or if it already has one), you should be able to use the OnMouseDown function in a script that is a component of your background sprite.
Here's an example:
using UnityEngine;
using System.Collections;
public class BackgroundManager : MonoBehaviour
{
GameObject gameManager; //The object that holds the gameManager script.
bool UIActive = false;
void OnMouseDown()
{
gameManager.GetComponent<GameManagerScript>().gameUI.SetActive(false);
}
}
If you intend to change a variable in your GameManagerScript class, you could do one of the following:
A) Get a reference to the gameobject that holds the GameManagerScript class as a component, then get a reference to that component.(I have the example script set up for this. :p)
B) Change your GameManagerScript class to a static class, meaning that all other scripts can access it.(You should note if you do this, that there would no longer be multiple instances of the script.)
Your answer
Follow this Question
Related Questions
Unity 4.6 2D,UI apears under game Sprite 1 Answer
Can't re-enable a gameobject 1 Answer
button.Select() and alternatives don't seem to work when called via new input system 1 Answer
is possible press 2 buttons at the same time Mobile touch? 0 Answers
Unity UI : Attached Gameobjetcs resets when starting the game 1 Answer