
Unity Cookbook
By :

The previous recipe demonstrated how to change the mouse pointer for 2D and 3D GameObjects receiving OnMouseEnter and OnMouseExit events. Unity UI controls do not receive OnMouseEnter and OnMouseExit events. Instead, UI controls can be made to respond to PointerEnter and PointerExit events if we add a special Event Trigger component to the UI GameObject:
Figure 2.25: Mouse pointer as a magnifying glass cursor
In this recipe, we’ll change the mouse pointer to a custom magnifying glass cursor when it moves over a UI Button
GameObject.
For this recipe, we’ll use the same asset files as we did for the previous recipe, as well as the CustomCursorPointer
C# script class from that recipe, all of which can be found in the 02_08
folder.
To set a custom mouse pointer when the mouse moves over a UI control GameObject, do the following:
IconsCursors
folder. Select all three images in the Project window and, in the Inspector window, change Texture Type to Cursor. This will allow us to use these images as mouse cursors without any errors occurring._Scripts
folder containing the CustomCursorPointer
C# script class.UI Button-TextMeshPro
GameObject to the scene, leaving this named Button.CustomCursorPointer
C# script class to the Button
GameObject.Button
GameObject selected in the Hierarchy window, drag the CursorZoom
image into the public Cursor Texture 2D variable slot in the Inspector window for the Customer Cursor Pointer (Script) component.Button
GameObject by going to Add Component | Event | Event Trigger.Button
GameObject into the Object slot.Figure 2.26: Event Trigger settings
OnMouseExit()
method from CustomCursorPointer when this event is received.In this recipe, you imported some cursor images and set their Texture Type to Cursor so that they could be used to change the image for the user’s mouse pointer. You also created a UI Button GameObject and added to it an Event Trigger component.
You then added an instance of the CustomCursorPointer
C# script class to the Button
GameObject and selected the magnifying-glass-style CursorZoom
image.
After that, you created a PointerEnter event and linked it to invoke the OnMouseEnter method of the instance of the CustomCursorPointer
script in the Button
GameObject (which changes the mouse pointer image to the custom mouse cursor).
Finally, you created a PointerExit
event and linked it to invoke the OnMouseExit method of the instance of the CustomCursorPointer
C# script class to the Button
GameObject (which resets the mouse cursor back to the system default).
Essentially, you have redirected PointerEnter
/Exit
events to invoke the OnMouseEnter
/Exit
methods of the CustomCursorPointer
C# script class so that we can manage custom cursors for 2D, 3D, and UI GameObjects with the same scripting methods.