In this article we are going to see how to change the cursor image when the pointer hovers over a button in Unity. In addition, a download package is provided with the scripts, sprites and the scene that is shown in the following video:
How to change the CURSOR IMAGE on HOVER in Unity
PLEASE CONSIDER SUBSCRIBING TO MY CHANNEL
A SHORT BREAK WITH THE LATEST NEWS
LET'S CONTINUE WITH THE ARTICLE
Download the Unity Package
Here you can download the Unity Package with the example on how to change the cursor image in Unity.
PLEASE CONSIDER SUBSCRIBING TO THE CHANNEL
PRESS "DOWNLOAD NOW!" TO DOWNLOAD THE FILE
Default Cursor Settings in Unity
This is something that can be done within a Start function, but if our game or application will have a custom cursor, for example a custom arrow, it is convenient to define it within the project parameters, going to Edit > Project Settings, the window shown in Figure 3 is displayed, there we can assign the default cursor Sprite, as well as its Hotspot coordinates.
Determining the Hotspot of our customized cursor
The hotspot of the cursor is the offset vector measured from the upper left corner of the Sprite and it indicates the point of the image where the tip of the cursor is considered to be. The script that comes in the package has fields defined to assign the Sprite of two cursors as well as the vectors of their respective Hotspots, as seen in the inspector in Figure 4.
To determine the Hotspots you have to enter the game mode and try different values until the cursor matches, another way would be to know exactly how many pixels horizontally and vertically is the point of the cursor.
How to change the cursor IMAGE in Unity
To change the image shown by the cursor just execute the instructions shown in figure 5, in lines 31 and 37, the SetCursor method inside the Cursor class, passing as parameter the sprite you want to show, the Vector2 with the position of the Hotspot and the cursor mode.
When to change the cursor image in Unity
In this particular case we are interested in constantly showing a default cursor until the pointer is positioned over a button, at that moment we want to show another different cursor to give feedback that the user can interact with that element. For this we need to be able to detect exactly when these events occur and for that I assign to each button an “Event Trigger” component and adding the “Pointer Enter” and “Pointer Exit” events.
To both events we assign the GameObject that has the Script with the functions that we want to execute (these functions must be defined as public) and then using the drop-down menu we choose the functions to execute in each event.