Serializing references to C2 object instances?

For developers using the Construct 2 Javascript SDK

Post » Tue Sep 12, 2017 1:25 am

What's the best way to serialize an array of references to C2 object instances?


Overview
I have a third-party behavior, that holds an array of references to C2 object instances. (These references are gotten from the SOL.)
This array is part of the behavior's internal state, with "this.references" being declared in the onCreate() function.

To get this behavior to cooperate with C2's native Save/Load state feature, I need to be able to save and load the behavior's internal state, using the saveToJSON() and loadFromJSON() functions.

The saveToJSON() returns an object to be serialized via JSON.stringify(), I think.

I think that JSON.stringify(), if given an array of C2 object refs, will try to serialize the entirety of each C2 object referenced. This causes a "Circular structure error", and isn't what I need to do anyway.
I don't want to serialize C2 objects, as all I need to save are the references to those objects.

Maybe I can get the UIDs of the referenced objects, and save those.
Then I can rebuild the correct references upon loading by looking up object instances by the saved UIDs.

Does anyone have advice on serializing an array of C2 object instances?
Any thoughts or sugestions are welcome. :)


Specific case
Finally, the specific behavior I'm trying to extend is Azis's "Store Reference" behavior:
behaviour-store-reference_t82224
I've already found and fixed some other problems with this behavior, but I just recently noticed it has no Save/Load support built in.
It's a nice idea for a behavior, but I'm just about at the point of replacing it with native UID-based events, since I know I won't have to fix anything else in the future if I just stick to event sheets.
B
27
S
18
G
8
Posts: 327
Reputation: 6,156

Post » Tue Sep 12, 2017 3:02 am

Yes, saving UID for instances reference is a possible solution, and you might need add "behinstProto.afterLoad" function to rebuild instances reference list. See official pin behavior for example.

Code: Select all
"uid": this.pinObject ? this.pinObject.uid : -1,

Code: Select all
this.pinObject = this.runtime.getObjectByUID(this.pinObjectUid);
B
108
S
26
G
267
Posts: 4,456
Reputation: 149,747

Post » Tue Sep 12, 2017 11:15 pm

That is super helpful @rexrainbow, thanks! :)

Looking at the pin behavior is a great suggestion.
I'm happy to hear there's an "afterLoad()" function, because I was wondering how to set up connections to things that might not be loaded yet.
B
27
S
18
G
8
Posts: 327
Reputation: 6,156


Return to Javascript SDK

Who is online

Users browsing this forum: No registered users and 1 guest