- Home /
Changing cursor on mouse hover?
I'll keep this quick and simple. I'm coding a button, and I want the cursor to change to a hand when it's moved onto this button. I can't quite figure it out. This is my code. I initialise the cursor texture to the cursor.jpg image I have in my Assets > Resources folder, and then I use Cursor.SetCursor to change the cursor. Maybe I'm doing something dumb. Any help would be greatly appreciated!
using UnityEngine;
using System.Collections;
public class ButtonBehaviour : MonoBehaviour
{
Texture2D cursor;
void Start ()
{
cursor = (Texture2D)Resources.Load ("cursor.jpg");
}
void OnMouseOver()
{
Cursor.SetCursor (cursor, Vector2.zero, CursorMode.Auto);
}
void OnMouseExit()
{
Cursor.SetCursor(null, Vector2.zero, CursorMode.Auto);
}
void Update ()
{
}
}
Answer by prefix · Dec 26, 2015 at 11:18 AM
Just be sure to change the texture type in the inspector to "cursor". Im not sure why you are initializing it when you can use it publicly. However if you want to keep it private, you can [Serializefield] and still manipulate the variable within the inspector.
public class ButtonBehaviour : MonoBehaviour
{
//if you want it private do:
[Serializefield]
Texture2D cursor;
//Otherwise you can do it publicly.
public Texture2D cursor;
void OnMouseEnter()
{
Cursor.SetCursor (cursor, Vector2.zero, CursorMode.Auto);
}
void OnMouseExit()
{
Cursor.SetCursor(null, Vector2.zero, CursorMode.Auto);
}
}
Please replace [Serializefield] with [SerializeField] in the code snippet.
This isn't any different than what the op is trying, $$anonymous$$us where the cursor asset is co$$anonymous$$g from...
Answer by Fdo_decea · Jul 07, 2018 at 08:28 PM
Any idea of how to make that change smoothly ?? I've tried with solutions too dirty and huge , trying to make a fade-out effect. There is also the problem that the textures have not alpha channel, so I have to go pixel to pixel fading them out. I would like to fade in, and fade out, using the default cursor and a custom one.