Is it possible to show and hide on command a PanelContainer using the variable "visible"?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Nat10

I am trying to make a PanelContainer appear and disappear at a given time using the variable “visible”, it only works if the function is executed inside “func _ready():”

:bust_in_silhouette: Reply From: Spyrex

When I create an empty scene, add a PanelContainer and attach the following example script it works perfectly fine:

# Toggles the visibility of the PanelContainer if any button is pressed    
func _unhandled_input(event):
	if event is InputEventKey && event.is_pressed():
		visible = !visible

So to spot the bug in your code, you have to reveal more of your project’s code.

Thanks, I tried your code and it works.
In my situation though, I would like to figure out how to call that function in my code. I have tried creating a new instance, but I get an error. So I would like to create functions that on command show and make the PanelContainer disappear, but they don’t work.

extends PanelContainer

func _ready() -> void:
	pass
	
func visibile():
	visible = visible
	pass
	
func nonvisibile():
	visible = !visible
	pass
	
func _unhandled_input(event):
	if event is InputEventKey && event.is_pressed():
		visible = !visible

Excuse my poor English and my ignorance in Godot, this is my first experience.

Nat10 | 2021-08-29 07:53

Ahh, this is a common issue every programmer runs into sooner or later.
Don’t get confused by variable names: “visible” is not a value by itself, but it is a property that contains the current value.


visible = visible

So setting the value of the variable “visible” to the current value of the variable “visible” will have absolutely no effect.


visible = !visible

In this case, the exclamation mark inverts the variable’s value. So if the variable “visible” contains the value “true”, the variable’s value will be set to “false” and vice versa.


To sum everything up, to always make the panel container visible when the function visibile() is called, just set the visible property to true. To hide it, set it to false.
Also good to know is that visible = !visible works as a switch. Every time it gets called it will toggle the current value of the variable.

PS: For best practises, rename your functions visibile() and nonvisibile() to something like make_visible() and make_invisible(). So it’s clear, they don’t return a value but set the property.

Spyrex | 2021-08-29 14:18