在Unity中不活动后如何使光标消失 [英] How to make cursor dissapear after inactivity in Unity

查看:216
本文介绍了在Unity中不活动后如何使光标消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标很简单,就像许多应用程序一样,我希望在用户闲置一段时间后使我的光标不可见.

My goal is simple, like a lot of applications, I want to make my cursor invisible after a certain time of inactivity of my user.

我的解决方案似乎没有真正地优化,这是算法:

My solution doesn't seem really optimized, here's the algorithm :

void Start {
    Timer t = new Timer(5000);//Create a timer of 5 second
    t.start();
}

void Update {
    if(MouseMoved){
        t.reset();
    }
    timeLeft = t.deltaTime;
    if ( timeLeft == 5000 )
    {
        Cursor.visible = false;
    }
}

我真的不希望在每一帧都检查,如果我的鼠标移动了,我宁愿我的鼠标移动会触发一些东西,但是我迷路了,有人能更好吗?解决方案?

I really don't like to check at every frame if the mouse is moved, I'd prefer that my mouse moved trigger something, but I'm lost here, is anyone have a better solution ?

推荐答案

我知道有两种方法可以在更新循环之外检查这种情况:

There are two ways to check for things like this outside of the update loop, that I know of:

1-自定义事件.

编写自己的自定义事件将使您可以在更新函数之外调用"OnMouseMove()"之类的内容,并且仅在鼠标光标的位置更改时才执行.

Writing your own custom event would allow you to call something like "OnMouseMove()" outside of the update function and it would only execute when the mouse cursor's position changes.

2-协程

创建一个单独的协程将使您执行此检查的频率降低.为此,您需要制作一个IEnumerator并将鼠标移动逻辑放在其中.像这样:

Creating a separate coroutine would allow you to perform this check less frequently. To do this, you make an IEnumerator and put your mouse movement logic in there. Something like:

IEnumerator MouseMovement()
{
    while(true)
    {
        if(MouseMoved)
        {
           //Do stuff
        }

        yield return new WaitForSeconds(1f);
    }
}

该协程在运行时每秒执行一次检查.您将通过说出协程开始:

That coroutine would perform the check once every second while it is running. You would start the coroutine by saying:

StartCoroutine(MouseMovement());

要阻止它,请致电

StopCoroutine(MouseMovement());

如果您在计时器到0时启动它,并在光标移动时停止它,则还可以防止协程程序始终运行,仅在光标处于非活动状态时使用它.

If you Start it when the timer reaches 0 and stop it when the cursor is moved, you can also prevent the coroutine from running all the time, only using it while the cursor is inactive.

这篇关于在Unity中不活动后如何使光标消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆