Tag Archives: mouse

Input: Detect Mouseover

  mouseover Unity has events that tell your scripts when the mouse cursor hovers over an object and stops hovering over an object. This can be great for UI or for prompting the player that they they can interact with something.


The <span style="font-size: 12pt;">OnMouseEnter()</span> method will run when the mouse cursor first enters the object’s collider area (the object must have a collider for this to work). [code languge=”csharp”] void OnMouseEnter() { // do something, e.g. change the sprite or make a sound } [/code]


The reverse method to <span style="font-size: 12pt;">OnMouseEnter()</span>, <span style="font-size: 12pt;">OnMouseExit()</span> is called when the mouse cursor exits the objects collider area. [code languge=”csharp”] void OnMouseExit() { // do something, e.g. change the sprite or make a sound } [/code]

Sample Script

This following script contains an example of what you can do with this functionality. Add this script to any object with the following:
  • A collider
  • A SpriteRenderer with a default sprite
  • Add a second sprite to the mouseOverSprite inspector field (the SpriteRenderer will show this sprite when the mouse cursor is over the GameObject).
[code language=”csharp”] using UnityEngine; using System.Collections; public class MouseOver : MonoBehaviour { [SerializeField] private Sprite mouseOverSprite; private Sprite defaultSprite; private SpriteRenderer sRenderer; void Start () { defaultSprite = gameObject.GetComponent&amp;lt;SpriteRenderer&amp;gt;().sprite; sRenderer = gameObject.GetComponent&amp;lt;SpriteRenderer&amp;gt;(); } void OnMouseEnter() { sRenderer.sprite = mouseOverSprite; } void OnMouseExit() { sRenderer.sprite = defaultSprite; } } [/code]

Expanding This

The Unity documentation has more details of this functionality (http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseOver.html). You can get inspiration for how to use this from the games you play. For games with a lot of UI this technique can bring those menus to life. You can do all kinds of transform tricks with it, such as:
  • Adjust an object’s scale
  • Add a slight rotation
  • Make a subtle sound
  • Animate the object.