[Unity2D/3D]改变鼠标的光标图标
单图标切换
- 把要替换的鼠标图标拖拽进Unity中,点击该图片,将其Texture Type类型替换为Cursor。
- 在File->Bulid Setting->Player Settings中选择要替换的鼠标图片
运行时出现此界面提示是因为将导入的鼠标图片改变为Cursor类型,在问你是否应用,点击Apply
注意!!:如果运行时鼠标图片是半糊半透明,就需要将图片从Cursor改成Sprite(2D and UI),这样就能达到预先效果
多图标切换:(以打地鼠为例)
在游戏的过程中经常要用到替换鼠标的图标的效果,在这里我以打地鼠游戏中切换锤子图标的效果来演示:
相关代码如下,不要忘记保存代码后将图片拖拽进脚本中;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class NewBehaviourScript : MonoBehaviour
{
//以打地鼠切换锤子为案例
public Image hammer; //定义一个图片
public Image hitCursor; //定义打地鼠的图片
public Image normalCursor; //定义不打地鼠的图片
// Start is called before the first frame update
void Start()
{
Cursor.visible = false; //隐藏正常鼠标
}
// Update is called once per frame
void Update()
{
if(Input.GetMouseButton(0)) //当按下鼠标左键 切换为击打的图片
{
hammer.sprite = hitCursor.sprite;
}
else
{
hammer.sprite = normalCursor.sprite; //当松开鼠标左键时 切换为正常的锤子图片
}
hammer.rectTransform.position = Input.mousePosition; //图片的位置跟随鼠标的位置
}
}
如果遇到了错误,请在下方的评论中给我留言,我会第一时间回复,谢谢。