0
\$\begingroup\$

Main question: How can I make this possible so that I can press a UI button inside the canvas while the cursor is locked?

Hello, I am creating a 3D video game. I have fully functional character control like walking using WASD keys and view rotation using mouse.

Now the last thing I need is to have cursor in the middle that can click on UI buttons on canvas like this:

https://www.youtube.com/watch?v=PPCwvqIqNxM&feature=youtu.be

I cannot click on UI buttons while the cursor is on locked constantly. So I created the pulse where the cursor will be locked and unlocked with a pulse so I can click on buttons.

This is the code I'm using:

//Inside the Update function.
float Lock = 0.0375f;
timer += Time.deltaTime;
if (timer > 0.02f && timer <= Lock)
{
    Cursor.lockState = CursorLockMode.Locked;
}
else if(timer > Lock)
{
    Cursor.lockState = CursorLockMode.None;
    if(timer >= Lock + 0.1f)
        timer = 0;
}
Cursor.visible = true;

It works, but not 100% proficient.

So, when I start building and run the game, here is what is happening:

https://www.youtube.com/watch?v=Fur6Al4zj3I&feature=youtu.be

What's happening is I cannot click the UI button after building and running the game. The only time I can press the button is when I am moving side by side while hovering over the button, otherwise if I stand still, I cant click the button.

This is the same crud I've been getting when I am designing one thing like a button for example, but when running, the button looks completely different from the designer. Same it applies here, I am running inside the Unity editor works, but when running inside the built game doesn't work like how it's suppose to.

For that, I just need help in what in the world I must do to make it work on both unity editor and built game, maybe I'm doing something wrong with the code? I need help. Any questions, please ask. Thank you.

\$\endgroup\$
1
\$\begingroup\$

Your code is fine, but logic is flawed. You cannot be sure that the cursor will be unlocked or locked at any given click, creating a possibility of unintended behaviour.

Instead, you can solve the problem using a global state machine:

UI Mode  <-A--  Game Mode
          --B->

During transition A: Unlock and show the cursor.

During transition B: Lock and hide the cursor.

\$\endgroup\$
  • \$\begingroup\$ I've used boolean and Button hover over script. Like anytime the pointer hovers over the button, the pulsing mode turns off and the cursor mode will be at none until the pointer leaves the button. \$\endgroup\$ – Sup Boy Apr 14 at 23:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.