- Home /
Detecting when a game object is clicked, when the mouse is held down, or enters or leaves a GameObject
I stumbled upon this post which was pretty useful:
http://answers.unity3d.com/questions/3209/basic-on-off-movement-using-mouse-click
My dilemma isn't exactly his though. His is more toggling a button while mine is a hold.
Problem 1: The button should de-activate when onMouseUp, easy modification, but it introduces another problem:
Problem 2: The button should de-activate when the mouse leaves its area. So if the guy drags his mouse off the button, it should deactivate.
Anybody know how to program this?
Thanks in advance!
Answer by duck · Jan 29, 2010 at 12:03 PM
There's an OnMouseExit event which you can use just like OnMouseUp, to trigger code when the mouse is no longer over the object. You'd probably have to use this in conjunction with the mouse up/down tests to get the effect you want.
(note, the comments appear to be wrong in the example on the documentation page linked above)
Here's an example which activates an object when clicked, and deactivates when the mouse is released, or when the mouse exits. Notice that it also reactivates if the mouse is brought back over the object while still held down (standard behaviour for normal Mac and Windows UI buttons). I'm using a boolean variable called 'wasClicked' to remember the state, to achieve this. The Activate() and Deactivate() functions are custom functions - I have just added code which makes the object change colour as an example, but you can put whatever you want in there.
var wasClicked : boolean;
function OnMouseDown() { wasClicked = true; Activate(); }
function OnMouseUp() { wasClicked = false; Deactivate(); }
function OnMouseEnter() { if (wasClicked) { Activate(); } }
function OnMouseExit() { Deactivate(); }
function Activate() { renderer.material.color = Color.red; }
function Deactivate() { renderer.material.color = Color.white; }
Thank you so much it works!!
How would I go about doing this for an iPhone seeing as how the iPhone doesn't have the mouse functions (I think)?
But since it haven't, this is what I could use for iphone: http://forum.unity3d.com/threads/15377-quot-On$$anonymous$$ouseDown()-quot-or-quot-On$$anonymous$$ouseUp-quot-On-GUIT
Do I assign this script to the object we want to whether is clicked or not?
Your answer
Follow this Question
Related Questions
C# Gameobject Rigidbody Mouse Collision 1 Answer
trying to move an object with the mouse 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
move Game Object(hand) with mouse movement 2 Answers
Best practice for copying Components from one GameObject to another? 3 Answers