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 and OS X default GUI.
If you need a set of textures to be used as cursor icons, please use the three image files available in the 0423_04_15
folder.
To implement custom mouse cursors, please follow these steps:
CursorScript
containing the following code:// file: CursorScript.cs using UnityEngine; using System.Collections; public class CursorScript : MonoBehaviour { public Texture2D iconArrow; public Vector2 arrowRegPoint; public Texture2D iconZoom; public Vector2 zoomRegPoint; public Texture2D iconTarget; public Vector2 targetRegPoint; private Vector2 mouseReg; void Start() { guiTexture.enabled = true; if (iconArrow) { guiTexture.texture = iconArrow; mouseReg = arrowRegPoint; Screen.showCursor = false; } } void Update() { Vector2 mouseCoord = Input.mousePosition; Texture mouseTex = guiTexture.texture; guiTexture.pixelInset = new Rect(mouseCoord.x - (mouseReg.x), mouseCoord.y - (mouseReg.y), mouseTex.width, mouseTex.height); if (Input.GetKey(KeyCode.RightShift) || Input.GetKey(KeyCode.LeftShift)) { if (iconTarget) { guiTexture.texture = iconTarget; mouseReg = targetRegPoint; } } else if (Input.GetMouseButton(1)) { if (iconZoom) { guiTexture.texture = iconZoom; mouseReg = zoomRegPoint; } } else { if (iconArrow) { guiTexture.texture = iconArrow; mouseReg = arrowRegPoint; } } } }
cursorZoom
when the right mouse button is clicked and to cursorTarget
when any Shift key is down.The script updates the GUI texture's position based on the mouse cursor position and registration points for each cursor type. The texture map is chosen according to the user's action (pressing the Shift key or clicking the right mouse button will change the texture). The script also hides the original mouse cursor, so it won't be on top of your custom one.
3.145.107.100