I'd like to serialize a Resource so that I can send it over a network in a networked game. That is, I'd like to take an instance of a custom class I've created, turn it into a PackedByteArray or a String or something like that, send it to the server with an RPC call and have the server decode it back into the original resource. Both the client and the server have scripts defining my resource object.

Godot does have a ResourceSaver, but this only writes to a file, not to a PackedByteArray. I've tried writing custom functions that produce a Dictionary, but this is both cumbersome and there is no clean way to decide what class has been sent when the server receives it. Is there some way to do in memory serialization for Resource extending objects?

Reload the resource file using FileAccess::get_file_as_bytes() or FileAccess::get_file_as_string.

4 months later

Is that common to use resources over json?

    I think Genie was specifically asking about serializing them to send over the network. And no, I don't think it's very common, at least in Godot

      award I see. Yeah, rather unusual. But could for example make sense if the game supports user created maps or something like that.

      If you do that, you probably also need to make sure you dont execute malicious code included in the resource, since functions get serialized too.

      5 months later

      Im having troubles with this aswell.

      In godot4:

      var_to_bytes_with_objects()
      bytes_to_var_with_objects()

      But the problem is when you try to bytes_to_var_with_objects it tries to cast the object type and add it to the current session, and if you have that type then it errors out.

      Is there a way to send custom object via rpc()??