How to make cursor dissapear after inactivity in Unity

后端 未结 2 1124
鱼传尺愫
鱼传尺愫 2021-01-26 05:13

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 s

相关标签:
2条回答
  • 2021-01-26 05:51

    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.

    0 讨论(0)
  • 2021-01-26 05:51

    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;
    }
    
    0 讨论(0)
提交回复
热议问题