Why does this code not toggle on/off the mouse cursor?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By DJSlimeball
var toggle = false

if Input.is_action_pressed("mouse_toggle"):
	Input.set_mouse_mode(Input.MOUSE_MODE_HIDDEN)
	toggle = !toggle
if Input.is_action_pressed("mouse_toggle") && !toggle:
	Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)

Sorry if this is a stupid question, I’m new.

:bust_in_silhouette: Reply From: jgodfrey

Something like this should work:

var mouse_visible = true

func _process(delta):
	if Input.is_action_just_pressed("mouse_toggle"):
		mouse_visible = !mouse_visible
		if mouse_visible:
			Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
		else:
			Input.set_mouse_mode(Input.MOUSE_MODE_HIDDEN)

It says that “‘mouse_visible’ isn’t declared in the current scope”? And when I remove “func _process(delta):” the error is gone but then the whole thing doesn’t work.

Also, how do I make the cursor not visible at first instead? Sorry but I didn’t think of it and want it that way actually.

P.S. Sorry for the late response.

DJSlimeball | 2022-11-18 05:47

I tested the code I posted, so I know it work (other than the updated question regarding starting with the cursor NOT visible).

For the first issue:

It says that “‘mouse_visible’ isn’t declared in the current scope”?

This code defines the variable at the scope of the entire script (and should be outside of any function). Did you not add this line?

var mouse_visible = true

Anyway, based on the new request to start with the cursor NOT visible, here’s a cleaner way (so, a complete replacement for the code above)…

func _ready() -> void:
	toggle_mouse_visibility()
			
func toggle_mouse_visibility():
	if Input.mouse_mode == Input.MOUSE_MODE_VISIBLE:
		Input.mouse_mode = Input.MOUSE_MODE_HIDDEN
	else:
		Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
		
func _process(delta):
	if (Input.is_action_just_pressed("mouse_toggle")):
		toggle_mouse_visibility()

Here, all the work of toggling cursor visibility is handled by the toggle_mose_visibility() function. Each time it’s called, the visibility is changed to the opposite of what it was previously. So, it’s called each time the mouse_toggle action is triggered.

Additionally, it’s called once from _ready() to set the initial state to HIDDEN

jgodfrey | 2022-11-18 15:00

THANKS! This worked! And also I did put “var mouse_visible = true” outside of it, no idea why it didn’t work.

DJSlimeball | 2022-11-19 00:32