Unity OnMouse Event Functions
Notes:
Unity On Mouse Event Functions / Methods:
- There are set of Mouse Event Methods as part of the MonoBehaviour class; which allow us to handle simple operations or logics based on Mouse inputs.
- are executed on a game object with Collider & an UI element; which has the script attached with mouse event methods.
void OnMouseEnter(){}:
- is called as soon as the mouse pointer enters a game object's bounding area
void OnMouseOver(){}:
- is called as long as the mouse pointer is over a game object's bounding area
void OnMouseDown() {}:
- is called as soon as the left mouse button is pressed on a game object's bounding area
void OnMouseDrag(){}:
- is called as long as the left mouse button is pressed and held down over the screen
void OnMouseUp() {}:
- is called as soon as the left mouse button is released on the same object or anywhere else on the screen
void OnMouseUpAsButton() {}:
- is called as soon as the left mouse button is released on the same object on which left mouse button was pressed
void OnMouseExit() {}:
- is called as soon as the mouse pointer exits a game object's bounding area
Note:
- are not called on objects that belong to Ignore Raycast layer
- are not called on Triggers; if their Physics.queriesHitTriggers is false
Example Code:
using UnityEngine;
public class CubeController : MonoBehaviour {
MeshRenderer mr;
void Start()
{
mr = this.GetComponent<MeshRenderer> ();
mr.material.color = Color.white;
}
void OnMouseEnter()
{
Debug.Log ("Mouse Enter");
mr.material.color = Color.red;
}
void OnMouseOver()
{
//Debug.Log ("Mouse Over");
}
void OnMouseDown()
{
Debug.Log ("Mouse Down");
mr.material.color = Color.green;
}
void OnMouseDrag()
{
Debug.Log ("Mouse Drag");
this.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y,10f));
}
void OnMouseUp()
{
mr.material.color = Color.red;
Debug.Log ("Mouse Up");
}
void OnMouseUpAsButton()
{
//Debug.Log ("Mouse Up As Button");
}
void OnMouseExit()
{
mr.material.color = Color.white;
Debug.Log ("Mouse Exit");
}
}