Variable assigned to operation won't update

Godot Version

4.6

Question

i’m trying to make a generator for an incremental game (like something that’ll generate x amount of currency every y seconds) and everything works, except my statue_cost won’t update even though statue_num does

the operation runs, if i change statue_num at start, statue_cost will return the correct amount, and statue_num is updating correctly as there’s an in game display of it. but statue_cost will always print 10 no matter what i do

var statue_num = 0.0
var statue_mult = 1.2
var statue_output = 0.0
var statue_cost = 10.0*(pow(statue_mult,statue_num))

func _on_statue_button_pressed():
	if Global.faith >= statue_cost:
		statue_num += 1
		statue_timer.start()
		Global.faith -= statue_cost
		statue_output += 1
		holy_shrine.set_visible(true)
		print(statue_cost)

func _on_statue_timer_timeout() -> void:
	Global.faith += statue_output

As far as I can tell, you never update statue_cost anywhere, so it always stays the same. The little calculation you wrote at the beginning will be calculated a single time, then it stays that for the duration of execution. You should make a function that does that calculation and returns the value you need. Otherwise that calculation will only run a single time when your game starts then never again.

when you declare a variable with var and you add = value you are just telling the script what the default value for that variable is

var myNumber = 10 
var myVariable = 5 + myNumber  ## default value = 15

if we later set myVariable = 9 then we just changed that variable from 15 to 9

so its better not to have a calculation on your default value.That could causes an issue later on if you try to @export the variable to edit it on the Inspector, it wont do the calculation in there


so what you could do is: store a variable called smt like statue_default_cost, default_statue_cost, base_statue_cost" or whatever you want. and this is what saves the default cost of the statues, while another variable is what shows you the current cost. as tibaverus suggested you could make a function that updates the value like so:

var statue_num = 0
var statue_mult = 1.2
var statue_output = 0.0
var statue_cost_current # this one updates when when we call the function

var _default_statue_cost = 10.0 # this stays the same through the game

func _ready() -> void:
	statue_cost_current = _default_statue_cost

func _get_statue_cost() -> float:
	return _default_statue_cost*(pow(statue_mult,statue_num))

func _on_statue_button_pressed():
	if Global.faith >= statue_cost:
		statue_num += 1
		statue_timer.start()
		Global.faith -= statue_cost
		statue_output += 1
		holy_shrine.set_visible(true)
		statue_cost_current = _get_statue_cost()

GDScript Reference > Variables