Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Cursor can't click in Locked mouse state

Discussion in 'Scripting' started by getmyisland_dev, Sep 18, 2021.

  1. getmyisland_dev

    getmyisland_dev

    Joined:
    Dec 22, 2020
    Posts:
    100
    I want my mouse cursor always in the center of my screen, but also I want to be able to click UI buttons.

    When I use
    Code (CSharp):
    1. cursor.Lockstate = CursorLockmode.Locked
    it stays in the middle of the screen, but it doesn't register hits anymore.

    I tried a little bit with raycasts to detect if I hit a UI button, but I can't get it to work, because it doesn't detect the buttons.

    Is there a way to get both keep the mouse cursor in the middle of the screen, but also be able to click UI buttons.
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
  3. LightID

    LightID

    Joined:
    Mar 11, 2021
    Posts:
    3
    Graf-enters likes this.
  4. AnomalusUndrdog

    AnomalusUndrdog

    Joined:
    Jul 3, 2009
    Posts:
    1,543
    The linked code works. Do you have a crosshair as a Unity UI Image? Turn off the Raycast Target on it since that Image might be receiving mouse clicks and preventing input from being used for whatever's underneath the crosshair.

    The only problem with the code posted is that it makes the cursor visible even while locked on the center. It seems rapidly changing Cursor.lockState within the same frame doesn't really work as expected.

    UnityEngine.EventSystems.PointerInputModule, unfortunately, just assumes that we always want the UI to be disabled when Cursor.lockState == CursorLockMode.Locked, it doesn't provide an option to circumvent that.

    Only way I was able to fix it is to copy-paste the underlying code of GetMousePointerEventData, ProcessMove, and ProcessDrag into that custom FirstPersonInputModule (instead of just calling the base methods), then removing the code that disables functionality when Cursor.lockState == CursorLockMode.Locked.

    It's not really an advisable thing to do, since it makes the FirstPersonInputModule potentially become incompatible if a version update of Unity UI ever comes that changes the code inside PointerInputModule.
     
    OfficeAcc likes this.