Cursor icons are often used to indicate the nature of the interaction that can be done with the mouse. Zooming, for instance, might be illustrated by a magnifying glass. Shooting, on the other hand, is usually represented by a stylized target. In this recipe, we will learn how to implement custom mouse cursor icons to better illustrate your gameplay—or just to escape the Windows, OSX, and Linux default GUI. The following screenshot shows a custom magnifying glass mouse cursor when the use's mouse pointer hovers over a Button:
For this recipe, we have prepared the images that you'll need in a folder named IconsCursors
in the 1362_01_13
folder.
To make a custom cursor appear when the mouse is over a GameObject, follow these steps:
IconsCursors
.CustomCursorPointer
, containing the following code, and add an instance as a scripted component to the Cube GameObject:using UnityEngine; using System.Collections; public class CustomCursorPointer : MonoBehaviour { public Texture2D cursorTexture2D; private CursorMode cursorMode = CursorMode.Auto; private Vector2 hotSpot = Vector2.zero; public void OnMouseEnter() { SetCustomCursor(cursorTexture2D); } public void OnMouseExit() { SetCustomCursor(null); } private void SetCustomCursor(Texture2D curText){ Cursor.SetCursor(curText, hotSpot, cursorMode); } }
CursorTarget
image into the public Cursor Texture 2D variable slot in the Inspector panel for the Customer Cursor Pointer (Script) component.CursorTarget
image that you chose.You have added a scripted object to a cube that will tell Unity to change the mouse pointer when an OnMouseEnter message is received—that is, when the user's mouse pointer moves over the part of the screen where the cube is being rendered. When an OnMouseExit event is received (the users mouse pointer is no longer over the cube part of the screen), the system is told to go back to the operating system default cursor. This event should be received within a few milliseconds of the user's mouse exiting from the collider.
There are some details that you don't want to miss.
Unity 5 UI controls do not receive the OnMouseEnter and OnMouseExit events. They can respond to the PointerEnter/Exit events, but this requires adding the Event Trigger components. To change the mouse pointer when the mouse moves over a UI element, do the following:
CustomCursorPointer
to the button.CursorZoom
image into the public Cursor Texture 2D variable slot in the Inspector panel for the Customer Cursor Pointer (Script) component.OnMouseExit()
method from CustomCursorPointer when this event is received.CursorZoom
image that you chose.18.116.80.34