My setget for doing something when an enum var is changed doesn't work

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

I created a day/night cycle and I have this for doing something whenever the state var is changed, however I tested it and the TIME_DAY or any stuff in the set_state doesn’t work. I am very new to Godot so I donno what to do, also tell me if my code is messy.

enum {
	DAY,
	DUSK,
	NIGHT,
	DAWN
}
var state = DAY setget set_state

and

func set_state(value):
	state = value
	match state:
		DAY:
			daylight.enabled = true
			moonlight.enabled = false
		DUSK:
			pass
		NIGHT:
			daylight.enabled = false
			moonlight.enabled = true
		DAWN:
			TIME_DAY += 1
			emit_signal("day_changed", 1)
			if TIME_DAY >= 30:
				TIME_DAY = 0
				TIME_MONTH += 1
				emit_signal("month_changed", 1)
			if TIME_MONTH >= 12:
				TIME_MONTH = 0
				TIME_YEAR += 1
				emit_signal("year_changed", 1)
			if timeUI != null:
				timeUI.text = str(TIME_DAY) + " " + str(TIME_MONTH) + " " + str(TIME_YEAR)
:bust_in_silhouette: Reply From: Kyle Szklenski

I would need to see how you’re calling the state changes. If you’re calling from the script that they’re defined in (like the above script), you have to call self.state = whatever. This will force it to call the setter. If you’re calling it from outside this script, well, I don’t have a guess at that point and would need to see more code (like where you’re calling the state changes).

i am changing the state var in the _process function of this script, so i assume i should do the self.state thing inside the set_state function? and will i have to do that also for everywhere else in the script that changes the state or just in set_state?

EDIT: actually i tried self.state = value instead of state = value and that didnt work so i probably misinterpreted where i need to put it

EDIT (again): I figured out where i need to put self.state and it works now, however the set_state func seems to be running every frame, making the TIME_DAY increase very quickly when it should only increase once.

EDIT (I should probably test more before typing): I figured it out, had to check if the state wasnt already the state it changes to

Hallamski | 2020-12-08 22:13