I need a global list ( variable[] ) in a game that I need to access thru python.
I know how to read and update a property variable of any object in a scene, but I need to retain a list (an array [ ])
Is that doable?
Thank you
I need a global list ( variable[] ) in a game that I need to access thru python.
I know how to read and update a property variable of any object in a scene, but I need to retain a list (an array [ ])
Is that doable?
Thank you
Itâs doable. What exact kind of list do you need?
Also see the global dictionary, you can plug whatever you like into it and access it from anywhere
You can store a list in a property too ;).
Why do you think you need a âglobalâ?
Why do you think you need a list?
I looked into the global dictionary and that works fine (See below). Thank you very much!
fyi- I am just used to using arrays in other programming languages, and thus Lists work for me within Python. I seemed to be restricted however because âadd game propertiesâ in the logic bricks only had âTimer, float, integerâ etc and I donât know how to initialize it as a list ( name[])
Hereâs what i found online about global dictionary and it worksâŚ
#assign values to a global list
bge.logic.globalDict[âplayer1â]= [âtonyâ,âarnoldâ]
##saved global dictionary
bge.logic.saveGlobalDict()
bge.logic.loadGlobalDict()
player1_Stats = bge.logic.globalDict[âplayer1â]
#the following prints out âtonyâ
print (player1_Stats[0])
In python you donât need to initalize things. So even if it was a string gwame property you could turn it into a list with a simple assignment.
You can also create properties at runtime with obj[ânewpropnameâ]
You also donât need to save load it every frame, saving it dumps it to a file on the hard drive.
Well, just to be clear on a few points,
The BGE doesnât support all Python data types, just a few (and an additional Timer type that doesnât really have an equivalent in Python).
You do need to initialized variables with values before you attempt to read them, or else the interpreter will throw an error. You donât need to initialize variables in the sense that any variable can be set from within Python without using the BGE types (though, again, thereâs no simple equivalent for the BGEâs Timer data type). Hereâs an example:
from bge import logic
cont = logic.getCurrentController()
obj = cont.owner
if 'init' not in obj:
obj['init'] = 1 # Initialize the "init" variable if it doesn't exist already
obj['items'] = {} # Create a Python dict and store it in the object with the variable name "items"
print(obj['items'])
I guess it is time for a deeper look onto datastructures and objrcts.
I suggest the first couple of BGE guides in my signature. It will help you to understand the BGE (it does not train you Python - there are other resources to do that).
Please use [noparse]
[/noparse] tags.
Please do not repeat code in comments. If you think your code needs explanations write it in a cleaner way.