Loop through objects and get ID in list


list = [object1, object2] #contains game objects

for obj in list:
    obj["prop"] = something
    logic.globalDict["something" + <i>the id of object in list</i>] = obj["prop"]

Now - how do I do the thing I underlined?


for i in (0, (len(list) - 1)):
    obj = list[i]
    obj["prop"] = something
    logic.globalDict["something" + str(i)] = obj["prop"]

Will this work?

Depends what you want to do with the key. If it is meant to be a player … call it “player”. If you have several players … you can store a list of players.

Which key you mean?

The key to the dictionary. You called it " ‘something’ + the id of object in list ".

I suggest you call it “somethings” and store a list of objects rather than a single object. Just make sure you create a list before you add the first object.

Unless bge somehow overwrites the builtin function, you can get a unique identifier for a python object by calling the predefined “id” function on the object itself. For example:

for obj in scene.objects:
   obj_id = id(obj)

In a python environment compliant with what we may call the “specifications”, that obj_id is unique for each object during its lifetime. From what I know, the only reason that might change in bge is due to the replacement of the reference that happens when you explicitly assign a KX_GameObject subclass instance to the underlying pointer.

Why you would save such an id in globalDict?

When you end the scene, the id and the according objects get invalid (the id might even be reused).
When you save that to file (which is the purpose of globalDict) it is invalid too as there is no according object anymore. There will not even be an according object after loading.

Hey, don’t ask me, he wanted an ID! :smiley: