- Home /
Cursor.visible doesn't hide cursor a second time.
Hi!
I am trying to create an fps game which hides the cursor hides in-game but appears in the pause menu. I am currently using Cursor.visible to hide the cursor every time I close the pause menu and make it appear every time I open the pause menu. Everything seems to work fine when opening the pause menu; The cursor appears and I can click and all that. But when I close the pause menu the cursor does not hide. This is my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class pause : MonoBehaviour
{
public GameObject pauseMenuCanvas;
public bool gamePaused = false;
public bool cursorVisible = false;
void Start()
{
pauseMenuCanvas = GameObject.Find("PauseMenu");
pauseMenuCanvas.SetActive(false);
}
void Update()
{
if (Input.GetKeyDown("escape")) {
gamePaused = !gamePaused;
cursorVisible = !cursorVisible;
}
if (gamePaused == true) {
Time.timeScale = 0.0f;
pauseMenuCanvas.SetActive(true);
}
if (gamePaused == false) {
Time.timeScale = 1.0f;
pauseMenuCanvas.SetActive(false);
}
Cursor.visible = cursorVisible;
}
}
It may not look very well made because I am fairly new to scripting with C#.
Any help would be greatly appreciated!!
Are you using Unity’s prebuilt character controller or a custom one? It is possible the controller might handle this too and therefore be overriding your code?
Are you testing this in the Editor or testing it in a build? Cursor stuff in the Editor is sometimes a bit weird. $$anonymous$$ake a build of your game, try it and see if you still have the cursor problem.
Answer by lgarczyn · Oct 12, 2019 at 02:57 PM
This is pretty weird.
I have one suggestion, which is to avoid setting the state of the cursor and the timescale every frame. Your code could look something like this:
void Update()
{
if (Input.GetKeyDown("escape")) {
gamePaused = !gamePaused;
if (gamePaused) {
Debug.Log("Pausing");
Time.timeScale = 0.0f;
} else {
Debug.Log("Unpausing")
Time.timeScale = 1.0f;
}
pauseMenuCanvas.SetActive(gamePaused);
Cursor.visible = gamePaused;
}
}
If this doesn't solve your problem, try to check if any other script is changing the cursor visibility. You could add a line to check for it, like this:
void Update()
{
Debug.Log("Cursor visibility before: " + Cursor.visible);
if (Input.GetKeyDown("escape")) {
[...]
}
Debug.Log("Cursor visibility after: " + Cursor.visible);
}
It will flood your logs, but you can simply explore them later. To reduce the amount of logs, reduce framerate, play the game frame by frame, or add a counter to only display this every few frames.
Your answer
Follow this Question
Related Questions
Cursor Toggle in Menu (UI) 1 Answer
How to click and drag images into multiple slots? 0 Answers
How to get the current cursor texture? 0 Answers
How to link buttons to individual levels within the same scene? 1 Answer
My UI Buttons stopped working 0 Answers