• Unity鼠标光标使用学习


    Unity下的鼠标光标程序相关的就一个类下的2、3个方法。

    首先,光标导入图片的设置需要将类型设置为Cursor。
    在这里插入图片描述
    设置鼠标光标的方法就一个,SetCursor。第一个参数是图片,第二个参数是点击点的偏移量,第三个参数是类型。

        public Texture2D texture;
        void Start()
        {
            Cursor.SetCursor(texture, new Vector2(40, 4), CursorMode.Auto);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    当使用CursorMode.Auto的时候,会使用硬件进行光标处理。性能好,兼容好。但是,在windows系统下,会强制把光标大小缩小到32*32。

    在这里插入图片描述

    当使用CursorMode.ForceSoftware的时候,会使用软件来处理光标。在windows系统下想要鼠标光标变大这是唯一的方法,但是偶尔会有小bug。在使用中发现unity2022.1+HDRP环境下,图片颜色会变深。

    在这里插入图片描述
    要实现图标动画的话,只能一张一张的图片轮流替换。CodeMonkey大佬有提供光标动画的代码,我就直接抄过来了。

    [CreateAssetMenu]
    public class CursorAnimation : ScriptableObject
    {
        public CursorType cursorType;
        public Texture2D[] textureArray;
        public float frameRate;
        public Vector2 offset;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    public class CursorMananger : MonoBehaviour
    {
        public CursorAnimation[] cursorAnimations;
        private CursorAnimation currentAnimation;
    
        private float frameRate;
        private int frameCount;
        private int currentFrame;
        private float frameTimer;
    
        private void Start()
        {
            SetActiveCursorAnimation(cursorAnimations[0]);
        }
    
        private void Update()
        {
            frameTimer -= Time.deltaTime;
            if (frameTimer <= 0f)
            {
                frameTimer += frameRate;
                currentFrame = (currentFrame + 1) % frameCount;
                Cursor.SetCursor(currentAnimation.textureArray[currentFrame], currentAnimation.offset, CursorMode.Auto);
            }
    
            if (Input.GetKeyDown(KeyCode.A)) SetActiveCursorAnimation(cursorAnimations[(int)CursorType.Arrow]);
            if (Input.GetKeyDown(KeyCode.S)) SetActiveCursorAnimation(cursorAnimations[(int)CursorType.Star]);
        }
    
        private void SetActiveCursorAnimation(CursorAnimation value)
        {
            currentAnimation = value;
            currentFrame = 0;
            frameTimer = value.frameRate;
            frameCount = value.textureArray.Length;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    B站光标效果演示视频:https://www.bilibili.com/video/BV1EN4y1j7Ne/

  • 相关阅读:
    自定义Maven Archetype模板工程
    css详细笔记
    关于我用iVX沉浸式体验了一把0代码项目创建(2)
    Spring Boot 面试题——常用注解
    用户级线程和内核级线程
    HTML期末作业-基于HTML+CSS+JavaScript制作学生信息管理系统模板
    7种设计模式
    webpack的loader和插件plugin
    C语言---插入排序、希尔排序、冒泡排序、选择排序、快速排序简单介绍
    下载安装nvm,使用nvm管理node.js版本
  • 原文地址:https://blog.csdn.net/wuyt2008/article/details/126185396