unity 更换鼠标图标,设置默认图标

工具:unity2018.4.2f1、VS2017

一、准备好鼠标样式,如图我用PS截取的鼠标图标(大小:70x70):

二、将图标放入工程,并设置图片类型,如图所示:

三、开始写代码,代码如下:

using UnityEngine;
using UnityEngine.UI;

public class ChangeMouseImage : MonoBehaviour
{
    //鼠标样式
    [SerializeField]
    Texture2D m_mouseStyle;

    bool m_isDefault = false;

    // Start is called before the first frame update
    void Start()
    {
        transform.Find("ChangeMouseBtn").GetComponent<Button>().onClick.AddListener(() =>ChangeImage());
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    void ChangeImage()
    {
        m_isDefault = !m_isDefault;

        //unity默认鼠标样式
        if (m_isDefault)
        {
            Cursor.SetCursor(null,Vector2.zero,CursorMode.Auto);
        }
        else
        {
            // 摘要:
            //     Specify a custom cursor that you wish to use as a cursor.
            //     指定要用作光标的自定义光标。
            //
            // 参数:
            //   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`.
            //    用于光标的纹理。要使用纹理,必须先导入它 启用“读 / 写”。或者,可以使用默认的光标导入
            //    设置。如果从代码创建光标纹理,则它必须为RGBA32格式,启用AlphaistTransparency,并且没有mip链。要使用默认光标,
            //    将纹理设置为“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.
            //     允许此游标在支持的平台上呈现为硬件游标,或强制软件光标。
            Cursor.SetCursor(m_mouseStyle,new Vector2(5,5), CursorMode.Auto);
            //这里第二个参数设置为5,5是因为我的鼠标图片存在空白像素
        }
    }
}

如图:

如果鼠标是充满整个图片的话,鼠标光标会偏大,不好看,所以我特意在周围添了些空白像素

 

注:脚本挂载在canvas上,不要忘记将图片拖到脚本上

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值