Evans Belloeil
Evans Belloeil

Reputation: 2503

How to make cursor dissapear after inactivity in 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 ?

Upvotes: 1

Views: 1572

Answers (2)

Jean-Michel Deboeur
Jean-Michel Deboeur

Reputation: 41

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;
}

Upvotes: 4

DisturbedNeo
DisturbedNeo

Reputation: 743

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.

Upvotes: 1

Related Questions