1
$\begingroup$

In BGE I want to use an object's property like a variable (for example to simulate speed increment for a car). How could I do it using a python script? And in this case could I use only "sensors" and "controllers" (using a python script as a "controller") without using "actuators"?

Sorry for my English. Thanks a lot...

$\endgroup$
2
$\begingroup$

You can see a property as "game object variable". This means it is part of the game object. (A variable is an separate object within a specific context e.g. a function).

Accessing a property the same like dictionary access.

Without check for existence:

propertyValue = gameObject[propertyName]

This fits in most situations. If the property does not exist you get a KeyError.

With pre-check:

if propertyName in gameObject:
    propertyValue = gameObject[propertyName]

This is a good situation when you can't guaranty the property is set, but you do not call this code very often.

With error handling:

try:
    propertyValue = gameObject[propertyName]
except KeyError:
    print("Warning: '{}' in {} does not exist.".format(propertyName, gameObject.name))

This is good when you expect the property might not be set and this situation is no reason to stop and this code is called very often (faster than pre-check).

With default value:

propertyValue = gameObject.get(propertyName, defaultValue)

This is good when you do not want to stop if the property is not set. In this case the default value will be given. Attention: The property will still not be set!

If you skip the default value, the default value is None. Be aware the default value is always evaluated, regardless if the property exists or not. Therefore the default value should be fast to get e.g. already exist or it is a primitive type such as numbers or strings.

Adding/updateing:

gameObject[propertyName] = newValue
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.