Search code examples
godotgdscript

How to use EncodedObjectAsID?


I'm trying to understand get_instance_id() and I came across this line in the documentation:

This ID can be saved in EncodedObjectAsID, and can be used to retrieve the object instance with @GDScript.instance_from_id.

I can't seem to understand what this statement means exaclty and how to use EncodedObjectAsID, could someone please provide a working example?


Solution

  • The EncodedObjectAsID follows a pattern called Boxing. Boxing is where you put a primitive value, like an int, into an object. This boxed primitive can now be used in an object oriented way. For example, you can pass the boxed int to a function that only takes objects (i.e. it applies Polymorphism):

    func only_takes_object(obj: Object)
    only_takes_object(123) # Error
    var box = EncodedObjectAsID.new()
    box.object_id = 123
    only_takes_object(box) # Valid
    

    This is how parts of the editor use the EncodedObjectAsId object.

    In marshalls.cpp we can see that an encoded Object may be an integer ID or the whole object. When it is flagged as only an integer ID a EncodedObjectAsID object is created. This object is then converted to a Variant.

    When adding a stack variable in editor_debugger_inspector.cpp a variant with a type of object is assumed to be and converted to an EncodedObjectAsID to fetch the referenced object's id.

    Here's two more links that follow a similar pattern:

    1. array_property_edit.cpp
    2. scene_debugger.cpp

    Note that Variant can be implicitly converted to an Object and Object::cast_to() only takes Objects.

    This ID can be saved in EncodedObjectAsID, and can be used to retrieve the object instance with @GDScript.instance_from_id.

    This sentence should be split into two independent clauses. It should read as

    • "The instance ID can be saved in an EncodedObjectAsID."
    • "The instance ID can be used to retrieve the object instance with @GDScript.instance_from_id()."

    Note: You should not store an object's id in storage memory. There is no guarantee that an object's id will remain the same after restart.