
上QQ阅读APP看书,第一时间看更新
How to do it...
To make a custom cursor appear when the mouse is over a GameObject, follow these steps:
- Create a new Unity 2D project.
- Import the provided folder, called Images. Select the unity_logo image in the Project panel, and in the Inspector change the 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).
- Add a 2D Object | Sprite GameObject to the scene. Name this New Sprite, if this wasn't the default name when created.
- In the Inspector, set the Sprite property of the Sprite Renderer component to the unity_logo image. In the GameObjects Transform component, set the scaling to (3,3,3), and if necessary, reposition the Sprite to be centered in the Game panel when the Scene runs.
- Add to the Sprite GameObject a Physics 2D | Box Collider. This is needed for this GameObject to receive OnMouseEnter and OnMouseExit event messages.
- Import the provided folder called IconsCursors. Select all three images in the Project panel, and in the Inspector, change the Texture Type to Cursor. This will allow us to use these images as mouse cursors without any errors occurring.
- 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; 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); } }
Event methods OnMouseEnter() and OnMouseExit() have been deliberately declared as public. This will allow these methods to also be called from UI GameObjects when they receive the OnPointerEnterExit events.
- With the New Sprite item selected in the Hierarchy, drag the CursorTarget image into the public Cursor Texture 2D variable slot in the Inspector for the Customer Cursor Pointer (Script) component.
- 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.