How to change labels of all nodes when some other label changes?

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

Hello, i have three instances of a scene containing a button and a label in my main node. I want change a label that is a child of a button after i click that button but all the other labels should reset. For example if i press Button1, Label1 changes, then I press Button2 and Label2 should change but Label1 should reset. I tried to connect main scene with a button pressed signal but I couldnt figure out how to know which button emited the signal and how do i reset text in all labels but not the one that should be changed. Thanks for help.

Do you need the scenes to be instanced? You can just make the nodes seperate and connect each button to its own function.

Bubu | 2021-04-06 08:59

How you createe those instances?
If you did it from the editor then every one has different name. So you can the labels with get_child(n) function. If the scenes have an Node2d for example and the button and label are children, then you can use $SceneName.get_child(0) to access the button and $SceneName.get_child(1) to access the label.

dancaer69 | 2021-04-06 16:28

:bust_in_silhouette: Reply From: Legorel

Following your exemple, I found this working:

MainScene has a button and a control node (the container for the TemplateScene intances)
TemplateScene has a button and a label

extends Node

# the button change the scene inside the container node
onready var switch_scene_button = $Button
onready var container = $Container

onready var template = preload("res://Scenes/TemplateScene.tscn")
# create the scene instances
onready var scene1 = template.instance()
onready var scene2 = template.instance()
# get the button and label of each scene
onready var button1 = scene1.get_node("Button")
onready var button2 = scene2.get_node("Button")
onready var label1 = scene1.get_node("Label")
onready var label2 = scene2.get_node("Label")

# which scene is currently displayed in the container
var current_scene = 1

func _ready():
  # connecting signals
  switch_scene_button.connect("pressed", self, "switch_scene")
  button1.connect("pressed", self, "button1_pressed")
  button2.connect("pressed", self, "button2_pressed")
  # default values
  button1.text = "Active"

# remove the current scene in the container and add the next scene
func switch_scene():
  for n in container.get_children():
  if current_scene == 1:
    current_scene = 2
  elif current_scene == 2:
    current_scene = 1

# change the text of the labels
func button1_pressed():
  label1.text = "Active"
  label2.text = "Inactive"

# change the text of the labels
func button2_pressed():
  label2.text = "Active"
  label1.text = "Inactive"