Reader small image

You're reading from  Unity Cookbook - Fifth Edition

Product typeBook
Published inNov 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781805123026
Edition5th Edition
Languages
Tools
Right arrow
Authors (3):
Shaun Ferns
Shaun Ferns
author image
Shaun Ferns

Shaun is a lecturer at Technological University Dublin. He is currently teaching on the BA (Hons) in Creative Digital Media where he is lead in the delivery of the Multimedia Stream. He is currently exploring serious games for construction-related training as well as the opportunities transmedia provides in improving user experience and engagement in cultural archive artifacts. His educational research is currently driven by his interest in self-determined learning (heutagogy), rhizomatic learning theory, micro-credentialing /digital badging, and curriculum development.
Read more about Shaun Ferns

Sinéad Murphy
Sinéad Murphy
author image
Sinéad Murphy

Sinead Murphy is currently Data Analytics Manager for the Irish NGO Trocaire. She has over 25 years of computing experience, including freelance IT training and database consulting, university lecturing in mathematics, IT skills and programming at TU Dublin (Ireland) and Middlesex University (London). She is a published academic, with undergraduate and postgraduate degrees in mathematics, computing and data science. She is passionate about the use of IT for understanding and visualising data, and using that understanding to make meaningful differences in the world. She is currently exploring the use of Python and Unity for data analytics and interactive visualisations.
Read more about Sinéad Murphy

View More author details
Right arrow

Setting custom mouse cursors for 2D and 3D GameObjects

Cursor icons are often used to indicate the nature of the interactions 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 or reticle:

A picture containing text

Description automatically generated

Figure 2.23: Mouse pointer represented as a stylized target

The preceding screenshot shows an example of the Unity logo with the cursor represented as 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, macOS, and Linux default UI.

Getting ready

For this recipe, we have prepared the folders that you’ll need in the 02_07 folder.

How to do it...

To make a custom cursor appear when the mouse is over a GameObject, follow these steps:

  1. Create a new Unity 2D project.
  2. Import the provided folder, called Images. Select the unity_logo image in the Project window. Then, in the Inspector window, change Texture Type to Sprite (2D and UI). This is because we’ll use this image for a 2D Sprite GameObject and it requires this Texture Type (it won’t work with the Default type).
  3. Go to GameObject | 2D Object | Sprites | Square to add the necessary GameObject to the scene. Name this New Sprite, if this wasn’t the default name when it was created:
    • In the Inspector window, set the Sprite property of the Sprite Renderer component to the unity_logo image. In the GameObject’s Transform component, set the scaling to (3,3,3) and, if necessary, reposition Sprite so that it’s centered in the Game window when the scene runs.
    • Go to Component | Physics 2D | Box Collider 2D to create a Box Collider and add it to the Sprite GameObject. This is needed for this GameObject to receive OnMouseEnter and OnMouseExit event messages.
  4. Import the provided folder called IconsCursors. 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.
  5. Create a C# script class called CustomCursorPointer containing the following code and add an instance as a scripted component to the New Sprite GameObject:
    using UnityEngine;
    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);
      }
    }
    

    The OnMouseEnter() and OnMouseExit() event methods have been deliberately declared as public. This will allow these methods to also be called from UI GameObjects when they receive the OnPointerEnterExit events.

  1. With the New Sprite item selected in the Hierarchy window, drag the CursorTarget image into the public Cursor Texture 2D variable slot in the Inspector window for the Custom Cursor Pointer (Script) component:

Figure 2.24: Cursor Texture 2D dragged to the variable slot

  1. Save and run the current scene. When the mouse pointer moves over the Unity logo sprite, it will change to the custom CursorTarget image that you chose.

How it works...

In this recipe, you created a Sprite GameObject and assigned it the Unity logo image. You imported some cursor images and set their Texture Type to Cursor so that they can be used to change the image for the user’s mouse pointer. You also added a Box Collider to the Sprite GameObject so that it would receive OnMouseEnter and OnMouseExit event messages.

Then, you created the CustomCursorPointer script class and added an instance object of this class to the Sprite GameObject. This script tells 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 Unity logo’s sprite image is being rendered. When an OnMouseExit event is received (the user’s mouse pointer is no longer over the cube part of the screen), the system is told to go back to the operating system’s default cursor. This event should be received within a few milliseconds of the user’s mouse exiting from the collider.

Finally, you selected the CursorTarget image to be the custom mouse cursor image the user sees when the mouse is over the Unity logo image.

Previous PageNext Page
You have been reading a chapter from
Unity Cookbook - Fifth Edition
Published in: Nov 2023Publisher: PacktISBN-13: 9781805123026
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Authors (3)

author image
Shaun Ferns

Shaun is a lecturer at Technological University Dublin. He is currently teaching on the BA (Hons) in Creative Digital Media where he is lead in the delivery of the Multimedia Stream. He is currently exploring serious games for construction-related training as well as the opportunities transmedia provides in improving user experience and engagement in cultural archive artifacts. His educational research is currently driven by his interest in self-determined learning (heutagogy), rhizomatic learning theory, micro-credentialing /digital badging, and curriculum development.
Read more about Shaun Ferns

author image
Sinéad Murphy

Sinead Murphy is currently Data Analytics Manager for the Irish NGO Trocaire. She has over 25 years of computing experience, including freelance IT training and database consulting, university lecturing in mathematics, IT skills and programming at TU Dublin (Ireland) and Middlesex University (London). She is a published academic, with undergraduate and postgraduate degrees in mathematics, computing and data science. She is passionate about the use of IT for understanding and visualising data, and using that understanding to make meaningful differences in the world. She is currently exploring the use of Python and Unity for data analytics and interactive visualisations.
Read more about Sinéad Murphy