Suggest a change
Success!
Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.
Close
Submission failed
For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.
Close
Your name
Your email
Suggestion*
Cancel
Description
Sets the mouse cursor to the given texture.
Call this method with a Texture2D to change the appearance of the hardware pointer (mouse cursor).
The cursorMode parameter allows you to use hardware cursors on supported platforms, or force software rendering of the cursor.
In the following example, the mouse cursor is changed to a given texture when OnMouseEnter is called, and reset to default when OnMouseExit is called.
Parameters
| texture | The texture to use for the cursor. To use a texture, you must first import it with `Read/Write`enabled. Alternatively, you can use the default cursor import setting. If you created your cursor texture from code, it must be in RGBA32 format, have alphaIsTransparency enabled, and have no mip chain. To use the default cursor, set the texture to `Null`. |
| hotspot | The offset from the top left of the texture to use as the target point (must be within the bounds of the cursor). |
| cursorMode | Allow this cursor to render as a hardware cursor on supported platforms, or force software cursor. |
Description
Specify a custom cursor that you wish to use as a cursor.
Call this method with a Texture2D to change the appearance of the hardware pointer (mouse cursor).
Join the Discord. Talk about Game Dev. Talk about Gaming.
This is a quick guide on how to make a 2D, custom mouse cursor in Unity, from making the texture, getting it into Unity, and then actually using it in your game.
The Texture
The first thing you need is a custom mouse texture. I recommend saving it as a PNG, or otherwise JPEG. According to some quick research, the Windows cursor seems to typically be either 32×32 pixels or 48×48 pixels.
The game I recently made, Puzzledorf, uses 12×12 pixel sprites, so I made the custom mouse cursor at the same size. However, I increase all of the graphics by 4x when I export, making the cursor 48×48 pixels on screen. The end result in Puzzledorf looks like below:
You can see from the above screenshot how a 48×48 pixel mouse cursor looks in a game at HD resolution. Try experimenting with a few different sizes if you’re not sure, like: 32×32, 48×48, and maybe 24×24.
Bear in mind, though, that the cursor can look quite different when testing inside Unity. The above screenshot is from an actual build in full HD. Below is what the 48×48 cursor looks like inside Unity:
Don’t ask me why Unity does something so bizarre, it simply does and I haven’t yet found a way around it, but it will look fine in the build if it’s full screen. If you use Windowed mode or a smaller resolution, it will look less nice.
Note: I actually took mouse control out of the menus in the final product of Puzzledorf but the above is what I did during development.
Importing The Texture For Use
Once you have your final cursor image, just put it inside your Assets folder in Unity, then click on the image and set it’s import settings as follows:
The most important part is having the Cursor texture type.
Using Clamp I believe helps the image to remain crisp and not blur or get weird visual glitches. Using Point (no filter) also helps achieve crisp 2D images, especially for pixel art.
I am not entirely sure why but having the Format as RGBA 32 bit is the way that Unity seems to prefer it.
The Code
To get your cursor in is really simple. Make a new CustomMouseCursor script as follows:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CustomMouseCursor : MonoBehaviour
{
public Texture2D mouseCursor;
Vector2 hotSpot = new Vector2(0,0);
CursorMode cursorMode = CursorMode.Auto;
private void Start()
{
Cursor.SetCursor(mouseCursor, hotSpot, cursorMode);
}
}
That’s it. Now just save that script, attach it to a game object in a scene, and drag your texture for the cursor onto the public variable mouseCursor in the inspector.
Below is an explanation of the code:
- public Texture2D mouseCursor is your mouse cursor texture
- Vector2 hotSpot is the point where clicks are registered on your mouse cursor, 0,0 is the top left corner of the texture
- CursorMode cursorMode defines how you want the texture rendered
private void Start()
{
Cursor.SetCursor(mouseCursor, hotSpot, cursorMode);
}
Start() runs when the game object in the scene becomes active.
Cursor.SetCursor() is a function that allows us to set the mouse cursor. We give it:
- the texture of the mouse cursor.
- where the hot spot of the cursor should be. It’s where your clicks are registered. 0,0 means you will click from the top left of the texture.
If you are using a cross-hair, and want the hot spot to be the center of the cursor, then set the position to halfway, ie, if your texture is 48×48 pixels, use Vector2 (24, 24) and then the clickable space should be the center of your cursor.
- The cursor mode, which gives you two modes, Auto and ForceSoftware. Auto means it will try and use your custom mouse cursor, but if it can’t, it will switch back to the systems default mouse cursor. ForceSoftware will always try and force your custom mouse cursor, but it leaves you with no back up if something goes wrong.
If your cursor disappears between scenes, it’s probably because the game object your Custom Mouse Cursor script is attached was destroyed when you went between scenes.
Замена курсора
Замена курсора
Добрый день всем.Люди подскажите пожалуйста как изменить стандартный курсор мышки на свой?
skype : game.develop
-
GameDevelop - UNIт
- Сообщения: 81
- Зарегистрирован: 28 дек 2011, 14:55
- Откуда: Одеса
- Skype: game.develop
Re: Замена курсора
bomberest 31 мар 2012, 13:07
Скрыть курсор Screen.showCursor = false (вроде, так). Рисовать текстуру нового курсора в позиции курсора, который скрыт
-
bomberest - Старожил
- Сообщения: 538
- Зарегистрирован: 22 июн 2011, 14:38
- Откуда: Минск
-
- ICQ
Re: Замена курсора
Hargrim 27 июн 2012, 17:18
Попробовал сделать вот так:
Используется csharp
void Update()
{
ray = mainCamera.ScreenPointToRay(Input.mousePosition);
transform.position = new Vector3(ray.GetPoint(0).x, 50, ray.GetPoint(0).z);
}
Очень большая задержка. Есть другие варианты?
- Hargrim
Re: Замена курсора
Receptor 27 июн 2012, 17:49
Используется csharp
public Texture cursorImage; //в инспектре выбираем нужную картинку/текстуру
void Awake() {
Screen.showCursor = false; // выключаем отображение системного курсора
}
void OnGUI() {
Vector3 mousePos = new Vector3(Input.mousePosition); // вектор позицию мышки на экране
Rect pos = Rect(mousePos.x,Screen.height — mousePos.y,cursorImage.width,cursorImage.height); // задаем область прорисовки на экране, или что-то вроде того))
GUI.Label(pos,cursorImage); // рендерим рисунок курсора в позиции мыши на экране
}
могут быть ошибки.
-
Receptor - Адепт
- Сообщения: 1706
- Зарегистрирован: 22 ноя 2011, 07:09
- Откуда: Волгодонск
Re: Замена курсора
yura415 27 июн 2012, 21:03
Рукалицо
Используется javascript
public var mouseTexture:Texture2D;
function Awake () {
Screen.showCursor=false;
}
function OnGUI () {
var m:Vector2 = Event.current.mousePosition;
GUI.depth=0;
GUI.Label(Rect(m.x,m.y,mouseTexture.width,mouseTexture.height),mouseTexture);
}
Используется csharp
public Texture2D mouseTexture;
void Awake () {
Screen.showCursor=false;
}
void OnGUI () {
Vector2 m = Event.current.mousePosition;
GUI.depth=0;
GUI.Label(new Rect(m.x,m.y,mouseTexture.width,mouseTexture.height),mouseTexture);
}
-
yura415 - Старожил
- Сообщения: 567
- Зарегистрирован: 14 дек 2010, 08:27
-
- Сайт
Re: Замена курсора
Receptor 28 июн 2012, 04:25

-
Receptor - Адепт
- Сообщения: 1706
- Зарегистрирован: 22 ноя 2011, 07:09
- Откуда: Волгодонск
Re: Замена курсора
yura415 28 июн 2012, 08:42
Используется csharp
new Vector3(Input.mousePosition)
Вот это абсурд просто
http://docs.unity3d.com/Documentation/S … ctor3.html
— Конструктор Vector3 может принимать либо (x,y,z), либо (x,y).
Так же выведение Rect’a в отдельную переменную для производительности не есть хорошо, хотя не сильно оно и повлияет. Но если постоянно выносить все динамические Rect’ы в переменные, например, то это повлияет на производительность. Чем больше обращений к переменным и конструкторов Rect’а, тем хуже
-
yura415 - Старожил
- Сообщения: 567
- Зарегистрирован: 14 дек 2010, 08:27
-
- Сайт
Re: Замена курсора
Hargrim 28 июн 2012, 17:54
Попробовал. Задержка меньше, но все равно есть и ощущается. Как будто приложение тормозит из-за слабой машины.
Это единственный метод заменить курсор?
- Hargrim
Re: Замена курсора
Hargrim 29 июн 2012, 11:41
Нашел в сети следующие высказывания:
Unity does not yet support custom Hardware Cursors
и
I haven’t seen it in the feature list for Unity 4 so i can’t be certain if it will be included in that version
Так что либо курсор системы, либо лагающий свой. Печаль(
- Hargrim
Re: Замена курсора
yura415 29 июн 2012, 11:50
Gonzik писал(а):Нашел в сети следующие высказывания:
Unity does not yet support custom Hardware Cursors
и
I haven’t seen it in the feature list for Unity 4 so i can’t be certain if it will be included in that version
Так что либо курсор системы, либо лагающий свой. Печаль(
Не понимаю что у вас лагает, у меня всё нормально. Вам надо оптимизировать проект, а не ругаться на лагающий курсор
-
yura415 - Старожил
- Сообщения: 567
- Зарегистрирован: 14 дек 2010, 08:27
-
- Сайт
Re: Замена курсора
mp3 29 июн 2012, 12:14
Если у Вас что-то там лагает, делайте Ваш курсор об’ектом, и таскайте его Update‘ом.
Be straight, or go forward.
-
mp3 - Адепт
- Сообщения: 1071
- Зарегистрирован: 21 окт 2009, 23:50
Re: Замена курсора
yura415 29 июн 2012, 12:23
mp3 писал(а):Если у Вас что-то там лагает, делайте Ваш курсор об’ектом, и таскайте его Update‘ом.
Gonzik писал(а):Попробовал сделать вот так:
Используется csharp
void Update()
{
ray = mainCamera.ScreenPointToRay(Input.mousePosition);
transform.position = new Vector3(ray.GetPoint(0).x, 50, ray.GetPoint(0).z);
}
Очень большая задержка. Есть другие варианты?
В первом же посту автор так делал.
-
yura415 - Старожил
- Сообщения: 567
- Зарегистрирован: 14 дек 2010, 08:27
-
- Сайт
Re: Замена курсора
mp3 29 июн 2012, 12:40
На Update’те всё должно работать, как и на OnGUI (правда здесь смотря, на чём запускается).
Вьіложите сцену, что-бьі бьіло видно, что, да как у Вас тормозит.
Be straight, or go forward.
-
mp3 - Адепт
- Сообщения: 1071
- Зарегистрирован: 21 окт 2009, 23:50
Re: Замена курсора
Hargrim 29 июн 2012, 13:30
Вьіложите сцену, что-бьі бьіло видно, что, да как у Вас тормозит.
Приложил проект. Можно сбилдить и посмотреть. Виндовый курсор не отключал для сравнения.
Вам надо оптимизировать проект, а не ругаться на лагающий курсор
Как можно оптимизировать проект, состоящий из одного единственного скрипта в одну строчку?
У вас нет доступа для просмотра вложений в этом сообщении.
- Hargrim
Re: Замена курсора
seaman 29 июн 2012, 14:02
Вообще ни грамма не тормозит. 600-700 fps стабильно
- seaman
- Адепт
- Сообщения: 8351
- Зарегистрирован: 24 янв 2011, 12:32
- Откуда: Самара
Вернуться в Почемучка
Кто сейчас на конференции
Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 30



