Composition
You can assign an object (instance of a class) by referring from the game object to your instance e.g. by assigning it as value to a property.
import bge
from myClassDefinitions import MyClass
myInstance = MyClass()
owner = bge.logic.getCurrentController().owner
gameObject = owner
gameObject["myClass"] = myInstance # assign object to game object
print(gameObject["myClass"]) # get object via game object
Explanation
The game object and the instance of your class (object) are two separate objects.
After creation you assign your object (as reference) to a property of the game object. This means the game object knows how to get the object at any time later via gameObject["myClass"]
.
The object does not need to know the game object. If you really need you can create a cross reference (e.g. by storing a reference of the game object as attribute of the object).
Advantages
- any number of objects can be assigned to the same game object
- any number of game objects can refer to the same object
- the property name indicates the purpose of the referred object
- the property can be exchanged or even removed
- allows to avoid dependencies to BGE from within your own classes (you can test it with unittest, you can use it outside the BGE)
- can survive game object remove (e.g. on scene switch) when referred from outside the scene.
(this is another option)
Object replacement
The BGE allows to "replace an existing game object". It is a strange idea but allows to feel like subclassing. It is descibed in the BGE API.
Explanation
You create an instance of your class which subclasses KX_GameObject (or whatever you told your class should inherit from).
The game object in the scene will be replaced by the BGE when instantiating your class (that is why you need to deliver a game object to be replaced).
Your object inherits all attributes from the game object you delivered at instantiation.
When the game object dies your object dies too as it is the game object now.
Advantage
- single class
- can still use properties
- feels like a class
Disadvantage
- single class only
- replaces the game object (any previously made references to this object become invalid)
- dependency to a single game object type branch (you can't use the same inheritance for KX_Camera and KX_FontObject)
- will not survive ending the game object (e.g. on scene switch).