Is it possible to create my own functions and use them through the object. Here is an example:
i have 2 scripts:
func.py
import bge
def func():
print(obj.name)
script.py
import bge
from func import func
def main(c):
obj = c.owner
if 'init' not in obj:
obj['init'] = True
obj.func = func
obj.func()
Is something in this direction possible. This would be really awesome to extend the gameobject!! Or do I have to modify the bge code itself to create such type of functions?
functions can be added as methods to an existing instance object, python permits this so yes it is possible. here is an example
assuming you have already an instance obj called obj and it has a method called func1 you can call it like this
obj.func1()
so far so good
if you define a function called func2 like
def func2(): print("hello I am the second method")
in order to attach to the object all you have to do is this
objc.func2 = func2
observe the lack of parantheses
after this assignment you can call the method normally as expected
obj.func2()
the reason this can happen is that functions are objects so in this case you created a reference back to your function definition in the object. In short an object inside another object , isnt it fun ?
you can use this to even rename existing methods though the method still can be called by the original names you can add a secondary name that makes more sense to you
for example lets say you dont like func1 as name you can do this
Ok… I got it working!!!
I needed to create a custom KX_GameObject class before, that inherited from the main KX_GameObject class. And then I could put my own functions into that class!!
Great!
You may experience some problems because blender has the nasty habit of making some data ready only , so i am not sure the type of reaction that you going to have if you do this. And this is why i don’t find The blender Python API, at all pythonic. But generally is a good idea to create your own objects and classes and clean up all that mess.
And to be clear on this and use the correct terminology. Functions tied to an instance object are called “instance methods”,functions tied to a a class are called “class methods”. Variables inside an object are called attributes and so on.