Search code examples
c#unity-game-enginelockingcursor

Unity cursor lock when click on UI button


I want the script to work as follows: Recognize that cursor is pointed on the UI button and click on the button. When I am clicking out of the UI buttons cursor should disappear.

Right now it is working as follows: When I click the UI button first time after starting the game it is working correct. It is clicking the button. After I click on the other place, the cursor disappear and this is also correct. After I press ESC button cursor appear and AFTER that I am not able to click my UI button anymore. It is not recognized.

Please help. I have recorded video to show what is wrong and under is a code which I use.

using UnityEngine;
using UnityEngine.EventSystems;

public class ClickBlockDemo : MonoBehaviour
{
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Debug.Log("GetMouseButtonDown");
            // Check if the mouse was clicked over a UI element
            if (EventSystem.current.IsPointerOverGameObject())
            {
                Debug.Log("Button Clicked");
                Invoke("CursorIsActive", 0.1f);

            }
            else 
            {
                Debug.Log("CursorLockMode.Locked");
                Cursor.lockState = CursorLockMode.Locked;
            }
        }        
    }
    void CursorIsActive()
    {
        Debug.Log("CursorIsActive");
        Cursor.lockState = CursorLockMode.None;
    }
}

Right now it is working as follows: When I click the UI button first time after starting the game it is working correct. It is clicking the button. After I click on the other place, the cursor disappear and this is also correct. After I press ESC button cursor appear and AFTER that I am not able to click my UI button anymore. It is not recognized.


Solution

  • After you press ESC, the game window loses its focus, that's why you can see the cursor. When you click on the game window again, it gains the focus and the cursor restores its state: CursorLockMode.Locked which is the state you set at last.

    You need to decide when to change the state of the cursor, for instance, if you want the cursor state to change to CursorLockMode.None after pressing ESC, you need to write code.

    if (Input.GetKeyDown(KeyCode.Escape))
    {
        Cursor.lockState = CursorLockMode.None;
    }