Python Question

Hi I just need to know if this is possible,
How can I read a variable based on objects name and a number?

Example,

Object_Name = Cube
Number = 4

if GameLogic.Object_Name + “_” + Number == Something:
Do other things

But it would read the “if GameLogic.Object_Name + “_” + Number” part as,

if GameLogic.Cube_4 == Something:
Do other things

Hm, not sure what you want. If you’re looking to store and retrieve according to string, use a dictionary. It stores values according to keys.

# create a dictionary if it doesn't exist
try:
    GameLogic.myDict
except NameError:
    GameLogic.myDict = {} # create a dictionary

name = "Cube"
number = 4

GameLogic.myDict [name + "_" + str(number)] = 42 # store 42 in "Cube_4" key 


theAnswer = GameLogic.myDict ["Cube_4"] # retrieve value in "Cube_4"

print "theAnswer is " + str(theAnswer)


http://diveintopython.org/getting_to_know_python/dictionaries.html

If you are looking to use introspection – running python from python, try the exec command:

exec("theAnswer = GameLogic." + objectName + "_" + str(theNumber))
print theAnswer

The exec command is bad news, though, and should only be used when no other approach will work.

Haha Perfect!

Just needed to change

theAnswer = GameLogic.myDict [name + “_” + str(number)] # retrieve value in “Cube_4”

Thank you so much!