Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | Solarbear |
Sorry if the title is confusing, I don’t know how else to ask this. Basically I have five variables: p1health, p2health, p3health, p4health, and currentp (with the p standing for player). Let’s say I want to decrease the health of the current player. I want to write something like
{“p” + currentp + “health”} = {“p” + currentp + “health”} - 1
instead of
if (currentp == 1) :
p1health = p1health - 1
elif (current p == 2):
p2health = p2health -1
etc.
That way I only need one line of code instead of eight. However, I can’t figure out any syntax that will get this to work, and I don’t know how to describe my question easily enough for Google to know what I’m talking about.
Is this possible, and if so, how? Thanks in advance for any help!
To my knowledge, I don’t think that’s possible in GDScript (though it’s possible in some languages, like ActionScript 2). I think the closest thing you have for that effect is the dictionary, where you could do:
p_health["p" + currentp + "health"] -= 1 # you can use '-=' too
Although, since you can create new entries in a dictionary with that same syntax, you’ll probably want to guard against potential mistakes:
var p_name = "p" + currentp + "health"
assert( p_health.has(p_name) )
p_health[p_name] -= 1
assert
stops the game from running if the returned value is false, so if you don’t want that just replace it with an if
statement.
woopdeedoo | 2018-11-03 12:25
Thank you for your response! Honestly I’ve just started this so recently that I’m not even sure what the dictionary is, so I get something new to research, yay!
Thanks again!
Solarbear | 2018-11-04 16:32
Here’s a short introduction to dictionaries in Python. GDScript dicts have different methods which you can see here.
skrx | 2018-11-04 17:37