- Home /
Check if Mouse is on the buttons
Hello there! I'm making main menu when the mouse is on the buttons over screen a image will apears over right. I making the menu code only for gain experinece. I knew how to check if mouse is over a object using OnMouseOver, but how I can check if it's over/not over from start_button, creditos_button and quit_button function?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MainMenu : MonoBehaviour
{
public Texture title;
public Texture background_texture;
public Texture Start_texture;
public Texture Credits_texture;
public Texture Quit_texture;
void OnGUI()
{
background_box();
start_button();
credits_button();
quit_button();
}
void start_button()
{
GUI.Button(new Rect(Screen.height / 2 - 10, Screen.width / 2 - 30, 85, 25), "Start Game");
}
void credits_button()
{
GUI.Button(new Rect(Screen.height / 2 - 10, Screen.width / 2 + 5, 85, 25), "Credits");
}
void quit_button()
{
GUI.Button(new Rect(Screen.height / 2 - 10, Screen.width / 2 + 40, 85, 25), "Quit Game");
}
void background_box()
{
GUI.Box(new Rect(Screen.height / 2 - 40, Screen.width / 2 - 38, 150, 115), "");
}
void OnMouseOver()
{
}
}
Answer by Glurth · May 20, 2018 at 06:19 PM
-Store the rectangles you used to create those buttons.
-Then, in Update or OnGUI (not OnMouseOver), you can use https://docs.unity3d.com/ScriptReference/Input-mousePosition.html to get the position of the mouse.
-Compare the mouse position with each of those button Rects, to see if it contains the mouse position. (https://docs.unity3d.com/ScriptReference/Rect.Contains.html)
(the reason you don't use OnMouseOver, is because you want to detect a mouseover of those buttons, NOT a mouseover the monobehavior object itself.)
So I store this way, and I need to do next is just using mouseposition?
void start_button()
{
Rect start = new Rect(Screen.height / 2 - 10, Screen.width / 2 - 30, 85, 25), "Start Game");
GUI.Button(start);
}
Something like this I'd think... (untested)
if(start.Contains(Input.mousePosition) )
{
Debug.Log("mouse is over start button");
}
I'm receiving error CS0103: The name `iniciar' does not exist in the current context I'm try to call the function, but the ".Contains" cannot acess it.
void start_button()
{
Rect iniciar = new Rect(Screen.height / 2 - 10, Screen.width / 2 - 30, 85, 25);
GUI.Button(iniciar, "");
}
void Update ()
{
start_button();
if (iniciar.Contains(Input.mousePosition))
{
Debug.Log("mouse is over start button");
}
}
Answer by oussamahassini6 · May 22, 2018 at 04:49 PM
you can create a gameObject how follows the mouse position and create triggers for the button and OnTriggerEnter the mouse is over the buttons simple and briant
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Renderer on object disabled after level reload 1 Answer
Main menu load function in c# 2 Answers