Help with referencing a specific variable given a number argument

Godot Version

Godot 4.2

Question

I am working with this block of code:

func attack(num: int):
var attackUsed
if(num == 1):
attackUsed = "res://scenes/attacks/%s.tscn" % playerStats.attack1 # playerStats.attack1 is a string
elif(num == 2):
attackUsed = "res://scenes/attacks/%s.tscn" % playerStats.attack2
elif(num == 3):
attackUsed = "res://scenes/attacks/%s.tscn" % playerStats.attack3

This function is meant to return the kind of attack used based on the num variable. So for example, passing in 1 would return the attack1 scene. Is there a way of condensing this code further? I have similar if and elif stacks in my code and its cluttering up my code a lot.

Is playerStats a dictionary? Try this:

func attack(num: int):
	var attackUsed = "res://scenes/attacks/%s.tscn" % playerStats["attack" + str(num)]
1 Like

just this will do:

func attack(num: int):
var attackUsed
attackUsed = "res://scenes/attacks/%s.tscn" % str(num)

assuming your playerStast.attack1 is exactly 1==1, and playerStats.attack2 is 2==2

problem is it’s not, so you cant

there’s other choice too, using match:

func attack(num: int):
	var attackUsed
	match num:
		1:
			attackUsed = "res://scenes/attacks/%s.tscn" % playerStats.attack1 # 		playerStats.attack1 is a string
		2:
			attackUsed = "res://scenes/attacks/%s.tscn" % playerStats.attack2
		3:
			attackUsed = "res://scenes/attacks/%s.tscn" % playerStats.attack3

other things you can do is to actually store the attack num and playerStats.attack string into key and value of a DIctionary:
and actually use the Dictionary to link between num used so calling the respective playerStats.attack

1 Like

I see. I’ll look into match and Dictionary then. Thank you!

I’m new to Godot so I haven’t heard of a Dictionary until now. I’ll try it. Thank you!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.