Godot Version
Godot 4.2
Question
Hello! I started to learn Godot 4.2 a week ago. I’m a beginner in coding. As my first project, I’m developing a simple incremental idle game. I have 10 upgrade tiers in this game for upgrading gained currency per second. I wrote the first tier’s code like this:
func _on_cpu_button_pressed():
if goldAmount > cpu_cost or goldAmount == cpu_cost: # If player’s gold is enough to buy a cpu
cpu += 1 # Increase cpu by one
goldPerSecond += cpu_value # Increase GPS by cpu’s value
goldAmount -= cpu_cost
cpu_cost *= 2 # Make the cpu’s cost double
$upgradeButtonSound.play()
else:
show_error_message()
$clickErrorSound.play()
And it’s worked flawlessly. ( I know it’s probably very inefficient but it’s simple enough to me understand.) Then I started to write the same code for other upgrade tiers with copy-pasting. After the third one, I got bored and thought “Well maybe I can use a function to automate this?” By using the documentary I came up with this:
func handle_upgrade(upgrade_value, upgrade_cost, upgrade_variable):
if goldAmount >= upgrade_cost:
upgrade_variable += 1 # Increase the corresponding upgrade variable
goldPerSecond += upgrade_value # Increase GPS by the upgrade's value
goldAmount -= upgrade_cost
upgrade_cost *= 2 # Double the upgrade's cost
$upgradeButtonSound.play()
else:
show_error_message()
$clickErrorSound.play()
``
then used it with another upgrade button
func _on_ram_button_pressed():
print("Before upgrade: ram =", ram, "ram_cost =", ramCost)
handle_upgrade(ram_value, ramCost, ram)
print("After upgrade: ram =", ram, "ram_cost =", ramCost)
It prints:
Before upgrade: ram =0ram_cost =100ram_value =1
After upgrade: ram =0ram_cost =100ram_value =1
It correctly upgrades gold gained by seconds but it doesn’t remove the cost for it and also doesn’t double the cost for it. I’m lost.
The way I see it, it works for half of the variables while doesn’t work for the other half. Code is the same as manual writing and using a function to write it. Can anybody explain it, please?