good day,

I have some code attached to a button that when pressed makes a panel set to not visible by default show on screen:

func _pressed(): get_tree().get_root().get_node("Node/Button/Panel").show()

I want to add to this so that if the panel is showing and the button is pressed again it will hide it with .hide() but am unsure as to how i would write this. I tried messing around with an IF statement and bools but it felt wrong and nothing has worked so far. Also if there is a better/more obvious way of performing this that would be great too.

Something like this?

var has_button_been_pressed = false
func _pressed():
	var button = get_tree().get_root().get_node("Node/Button")
	var panel = button.get_node("Panel")
	
	if (panel.visible == true and has_button_been_pressed == true):
		button.visible = false
	else:
		panel.visible = true
		has_button_been_pressed = true

I'm not sure if it is really the best way of doing this, nor if it is better, but off the top of my head that is how I would handle it. Depending on how your project and UI is setup, you might be able to remove has_button_been_pressed and just use panel.visible for toggling the button's visibility. Hopefully this helps a bit!

You can do this, I think that is the simplest way:

onready var panel = get_node("/root/Node/Button/Panel")

func _pressed():
    panel.visible = !panel.visible

@cybereality said: You can do this, I think that is the simplest way:

onready var panel = get_node("/root/Node/Button/Panel")

func _pressed():
    panel.visible = !panel.visible

Had to change the get_node to get_tree().get_root().get_node() but from there it worked perfectly

2 years later

Hi ( I am not sure if this needs to be here or some where else but..) this is what I have so far SBLevel1A (root) Tilemap Platform1A SpongeBob [that is my player) camera2D Platform2A Button (AN AREA2D) Sprite collisionShape2D

Platform2D.GD (the script file) extends Node2D

func _ready() -> void: self.hide()

so far it is working great (see picture) what I need help with is when I hit the button I need Platform2A to appear beside the first platform

It's just a matter of saving a reference to the node you want to show or hide (using get_node("name")) and then calling visible = false or visible = true. You can also change the position x/y to whatever you want.

Yeah, no problem. I'm here to help. Also, Happy New Year!

a year later