Search Unity

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,553
    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.
  5. navarone77

    navarone77

    Joined:
    Jan 5, 2018
    Posts:
    5
    I'm currently stuck on this issue. Could you please explain a bit more what you mean by this?
    The UI now works but the cursor is visible.

    Having a bit of confusion what you did to fix, I'm not sure how to approach this fix.

     
  6. nosferathoo

    nosferathoo

    Joined:
    Sep 20, 2012
    Posts:
    6
    Sorry for digging this out but I came across this script and found that it makes cursor show and hide constantly and also influence the movement smoothness. Solution is to change CursorLockMode.None to CursorLockMode.Confined