touilleMan / godot-python

Python support for Godot šŸšŸšŸ
Other
1.83k stars 136 forks source link

Pass or return Python instance to/from Godot #386

Open tduhautb opened 1 year ago

tduhautb commented 1 year ago

Hello,

I'm trying to implement some sort of duplication mechanism with Python instances in order to use temporary results without altering my initial instance. My problem is that I can't find a way to either return a new instance from Python to Godot, or to pass an instance created in Godot to Python.

For the first option, returning a new instance from Python doesn't seem accepted by Godot:

# MyClass.py

@exposed
class MyClass(Object):
    # [...]
    def duplicate(self) -> "MyClass":
        new_instance = MyClass()
        # assign new_instance attributes from self
        return new_instance
# script.gd

var MyClass = preload("res://.../MyClass.py")
var instance = MyClass.new()
var instance2 = instance.duplicate() # -> instance2 is Null !

For the second option, I tried to pass a new instance created in the GDScript to copy the fields in the Python class directly, but I don't get the right class and I didn't find how to retrieve the Python instance:

# script.gd

var MyClass = preload("res://.../MyClass.py")
var instance1 = MyClass.new()
var instance2 = MyClass.new()
instance2.copy(instance1)
# MyClass.py

@exposed
class MyClass(Object):
    # [...]
    def copy(self, initial) -> None:
        # initial is a <godot.builtins.Object> and not a <MyClass> object, I can't access the attributes

Does somebody known how to overcome these issues?

I'm using Godot 3.5.1_stable and PythonScript 0.5.

Thanks !