This script allows you to rely on Unity UI to render the cursor, making it possible to add e.g. animation effects. It works by positioning a RectTransform to match the position of the system cursor. It can be used in one of two ways:
- Modify the texture field of a RawImage component to match the graphic AC wants to set its own cursor to
- Modify Animator parameters to control playback of animations that control the UI's appearance
To use the script:
- In the Cursor Manager, set the Cursor rendering field to Hardware
- Create a new Unity UI Canvas, and either create a RawImage component to act as the cursor, or configure an Animator to change the UI's appearance based on a "ClickID" integer, an "InventoryID" integer, a "CursorIsVisible" boolean, and "Click" trigger.
- Attach the script below to the Canvas and configure the Inspector to suit your needs.
UnityUICursor.cs:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using AC;
public class UnityUICursor : MonoBehaviour
{
public Texture2D emptyTexture;
public Animator _animator;
public string cursorIDIntParameter = "CursorID";
public string inventoryIDIntParameter = "InventoryID";
public string cursorVisibleBoolParameter = "CursorIsVisible";
public string clickTriggerParameter = "Click";
public RawImage rawImageToControl;
public RectTransform rectTransformToPosition;
private void OnEnable ()
{
if (KickStarter.cursorManager.cursorRendering == CursorRendering.Software)
{
Debug.LogWarning ("Cursor rendering must be set to 'Hardware' for the UnityUICursor script to take effect.");
}
EventManager.OnSetHardwareCursor += OnSetHardwareCursor;
}
private void OnDisable ()
{
EventManager.OnSetHardwareCursor -= OnSetHardwareCursor;
}
private void Update ()
{
if (_animator != null)
{
if (!string.IsNullOrEmpty (cursorIDIntParameter)) _animator.SetInteger (cursorIDIntParameter, KickStarter.playerCursor.GetSelectedCursorID ());
if (!string.IsNullOrEmpty (inventoryIDIntParameter)) _animator.SetInteger (inventoryIDIntParameter, (KickStarter.runtimeInventory.SelectedItem != null) ? KickStarter.runtimeInventory.SelectedItem.id : -1);
if (Input.GetMouseButtonDown (0))
{
if (!string.IsNullOrEmpty (clickTriggerParameter)) _animator.SetTrigger (clickTriggerParameter);
}
}
if (rectTransformToPosition != null)
{
rectTransformToPosition.position = Input.mousePosition;
}
}
private void OnSetHardwareCursor (Texture2D texture, Vector2 clickOffset)
{
Cursor.SetCursor (emptyTexture, Vector2.zero, CursorMode.Auto);
if (rawImageToControl != null)
{
rawImageToControl.texture = (texture != null) ? texture : emptyTexture;
}
if (_animator != null)
{
if (!string.IsNullOrEmpty (cursorVisibleBoolParameter)) _animator.SetBool (cursorVisibleBoolParameter, (texture != null));
}
}
}