Changing the value of a variable from other node

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

So i basically trying to make a calendar here and what i want to do is so that when i press the next month button, the text of the current month label will change to the next month.

So here’s the code of my monthlabel node. I use regular label node for this and I’ve add it into the autoload.

extends Label

var time = OS.get_datetime()
var currentmonth = time["month"]

var namemonth = ["null", "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"]
var monthname = str(namemonth[currentmonth])

func _ready():
	text = monthname

Then I thought this would work

But i guess it doesn’t and i don’t know what to do.

ps. sorry for the shitty english, not a native

:bust_in_silhouette: Reply From: Gluon

Its very simple you can just have the line

var text = ""

text = path_to_node.variable_name

so you just have a variable in another node and reference the path . the name of the variable.

:bust_in_silhouette: Reply From: Wakatta

Changing the value of a variable from other node

The workflow

  • Get the node reference
  • Get the value from the reference

Using the above workflow you will never need to use Autoloads once you know where the node is in the SceneTree and how to access it using get_node, find_node, get_child, find_parent / child.

Caution

Don’t rely on global vars for everything and instead use functions

Answer

extends Label

var namemonth = ["null", "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"]

func _ready():
    text = get_month_name()

func get_month_name(itr = 0):
    var time = OS.get_datetime()
    var currentmonth = time["month"] if itr == 0 else itr
    return str(namemonth[currentmonth])

Explanations

The line

var currentmonth = time["month"] if itr == 0 else itr

is a ternary which goes like

# if itr variable is equal to 0
# currentmonth = time["month"]
# else
# currentmonth = itr

The line func get_month_name(itr = 0): allows the function to be called without variables
by pre-setting itr to 0

:bust_in_silhouette: Reply From: deaton64

On the back of what @Gluon has said, you don’t have to attach scripts to everything you want to control.
You could have all the code in the script attached to MainScene and reference the text label like this:

$UI/VBoxContainer/Month/TextureRect/Label.text = monthname

or put have a variable hold the value, so if the object moves, you can easily change your code:

@onready var month_label: Label = $UI/VBoxContainer/Month/TextureRect/Label

then

month_label.text = monthname

oh yes you’re right. should’ve done it from the beginning
Thanks for the advice!

Numshv | 2022-11-13 00:13