One Variable has two values

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

i have the following code:

extends Node2D
var t 

func _ready():
	t = 1
func g():
	t= 3
	return t

func _physics_process(delta):

The function “func g()” will be activated of a signal during my game. But after it activated, “t” has the values “1” and “3”, which i could see, because i print “t” all the time with the function " func _physics_process(delta):" . How is it possible, that “t” has only the value “3”, after “func g()” is activated?
Thanks Nils

ready() is called once at the start and sets the value to 1. When you call g() that will overwrite the value previously set by ready() and set it to 3. From then on the value will continue to be 3 unless it is changed by another function. t will only ever be one value. It won’t be 1 and 3.

i_love_godot | 2019-12-21 00:38

:bust_in_silhouette: Reply From: kidscancode

_ready() is only called once, when the node enters the tree. At this point, t is set to 1 and every physics frame, 1 is printed.

When you call g(), the value of t is set to 3, so now the print statement will start printing 3s. Note that the return statement in g() is not really needed, as you’re modifying the class variable anyway.

This happens because t is declared as a class variable (or property - the terms are used interchangeably). That means that its scope is at the class level, so every method in the class has access to the variable.