How to make cursor dissapear after inactivity in Unity

二次信任 提交于 2020-05-24 05:36:12

问题


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 ?


回答1:


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

1 - Custom Events.

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 - Coroutines

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());

And to stop it, you call

StopCoroutine(MouseMovement());

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.




回答2:


This should be the good way to achieve the task, using coroutine, without any memory issue:

private Coroutine co_HideCursor;

void Update()
{
    if (Input.GetAxis("Mouse X") == 0 && (Input.GetAxis("Mouse Y") == 0))
    {
        if (co_HideCursor == null)
        {
            co_HideCursor = StartCoroutine(HideCursor());
        }
    }
    else
    {
        if (co_HideCursor != null)
        {
            StopCoroutine(co_HideCursor);
            co_HideCursor = null;
            Cursor.visible = true;
        }
    }
}

private IEnumerator HideCursor()
{
    yield return new WaitForSeconds(3);
    Cursor.visible = false;
}


来源:https://stackoverflow.com/questions/37618140/how-to-make-cursor-dissapear-after-inactivity-in-unity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!