- Home /
Prevents a mouse click on interface to trigger a click to move script
Hello all !
I have a classic click to move script (I am using Camera.main.ScreenPointToRay (Input.mousePosition); to detect the destination of the character)
However, I'd like to disable this script when my mouse is over interface elements (such as buttons, textures, etc.). For the moment, when I click on a button somewhere on my interface, it gives a move order, which is pretty annoying :)
Is there an easy way to do it ? (such GUI.depth or something like that which would prevent this behavior ?)
Thanks
Answer by xarasu · Jun 20, 2012 at 05:18 PM
I was looking for something similar but couldn't find a clean solution either. I've done it three ways.
Have a certain area of the screen designated for UI elements, say the bottom 40 pixels. Then in your move script, check to make sure it's above these 40 pixels and only do movement then. You can have some sort of texture over this area to help designate to the player that clicking there doesn't do anything.
Similar to the first, but a little more complicated. You can also store a list of rects that you add to each time you show a UI element and loop through it in the move function to make sure the mouse position isn't hovered over a UI element.
Inside the the move script have a bool for interfaceClicked. In each of your buttons actions you would need to set this bool to true, then in the move script's update function before you check for Input.mouseUp (or w/e you use to check for mouse clicks), if the bool is true, set it to false and return.
Script for the Button
if (GUI.Button ( new Rect (x, y, width, height), "Button Label")) {
MovementScript.selectedInterface = true;
doAction()
}
Movement script
void Update () { // Don't move if an interface was selected if (selectedInterface) { selectedInterface = false; return; }
// Selection
if ( Input.GetMouseButtonDown(0) )
{
moveUnit();
}
}
It's quite strange that there is nothing planned for this in Unity... Anyway, your solutions are correct.