Input: Detect 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.

Note: this is an older post that uses the old Unity input system. This will still work, but the new input system is more powerful and flexible.

OnMouseEnter()

The OnMouseEnter() method will run when the mouse cursor first enters the object’s collider area (the object must have a collider for this to work).

void OnMouseEnter()
{
   // do something, e.g. change the sprite or make a sound
}

OnMouseExit()

The reverse method to OnMouseEnter(), OnMouseExit() is called when the mouse cursor exits the objects collider area.

void OnMouseExit()
{
    // do something, e.g. change the sprite or make a sound
}

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).
using UnityEngine;
using System.Collections;

public class MouseOver : MonoBehaviour
{
    [SerializeField] private Sprite mouseOverSprite;
    private Sprite defaultSprite;
    private SpriteRenderer sRenderer;

    void Start ()
    {
       defaultSprite = gameObject.GetComponent<SpriteRenderer>().sprite;
       sRenderer =    gameObject.GetComponent<SpriteRenderer>();
    }

    void OnMouseEnter()
    {
       sRenderer.sprite = mouseOverSprite;
    }

   void OnMouseExit()
   {
       sRenderer.sprite = defaultSprite;
   }
}

Expanding This

The Unity documentation has more details of this functionality (https://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.

Leave a Comment