Cursor Lockstate for UI List

Hi everyone, I am trying to make a simple solution to check whether a UI gameobject is active or not so it will unlock or lock the cursor instead of scripting the same function into each separate gameobject or its main script.

The script works to an extent, however the cursor flickers all the time and sticks to the middle of the screen. Any guidance would be greatly appreciated.

I have this attached to the gameobject that is the UI Manager.

using System;
using UnityEngine;

public class MouseStateCheck : MonoBehaviour
{

    [Header("List of Openable UI")] public GameObject[] listUI;

    private void Update()
    {
        for (int i = 0; i < listUI.Length; i++)
        {
            if (listUI[i].activeInHierarchy)
            {
                // Enable cursor
                Cursor.lockState = CursorLockMode.None;
                Cursor.visible = true;
                // Pause the game
                Time.timeScale = 0f;
            }
            else
            {
                // Disable cursor
                Cursor.lockState = CursorLockMode.Locked;
                Cursor.visible = false;
                // Resume Game
                Time.timeScale = 1f;
            }
        }
    }
  
}

Anytime you fiddle with the Cursor a lot you’re probably going to have a bad time.

If you need custom mouse pointer behavior it is always going to be easiest to hide the OS cursor and then make and drive your own, which you can control precisely when and where it appears.

1 Like

Thanks, didn’t even think of that. The OS cursor is causing a lot of issues when testing. Will take the approach you supply! Thanks!!