Adding New Game Properties

2014/12/21 19:53

This is missing from the current Alpha 2.52 Python API:

#---------------------------------------------
# obj = object
# strName = name to give property
# type = "BOOL", "INT", "FLOAT", "STRING", or "TIMER"
# value = something appropriate
#---------------------------------------------
def CreateGameProperty(obj, strName, type, value):
    #create a list of the current game properties
    lstPropertyNames = []
    for prop in obj.game.properties:
        lstPropertyNames.append(prop.name)
         
    #check it's not already added
    if strName in lstPropertyNames:
        print("Error: Already Registered game property: " + strName)
        #you can edit this a little so that it overwrites the
        #existing game property, just don't do the stuff below
        #and call:
        # obj.game.properties[strName].name=strName
        # obj.game.properties[strName].type=type
        # obj.game.properties[strName].value=value              
        #but in this case we'll just return
        return
    #add the new property
    bpy.ops.object.game_property_new()
 
    #create a 2nd list
    lstNewPropertyNames = []               
    for prop in obj.game.properties:
        lstNewPropertyNames.append(prop.name)
 
    #find out the newly added property
    temp = list(set(lstNewPropertyNames) - set(lstPropertyNames))
 
    if len(temp) > 0:
        obj.game.properties[temp[0]].name=strName
        obj.game.properties[strName].type=type
        obj.game.properties[strName].value=value               
#enddef
 
#the below will add a float and string property to the "cube" object
CreateGameProperty(bpy.data.objects["Cube"],"float_value","FLOAT",1.0)
CreateGameProperty(bpy.data.objects["Cube"],"string_value","STRING","string")