Is it possible to spawn an object from JSON?

Get help using Construct 2

Post » Mon Oct 26, 2015 1:28 am

I'm aware of the ability to save an object's properties as JSON, but do those properties store the type of object it is as well?

I have a family of "enemy" sprites that I'd like to import/export using JSON. I can save the JSON of each enemy without an issue, but when attempt to restore them all, there's no way for me to know which JSON object belongs to which member of the family.

Is there a way to work around this? Does the JSON object even store the information I would need to make this work?
B
14
S
2
Posts: 73
Reputation: 794

Post » Tue Oct 27, 2015 5:09 pm

You should add a "type" tag to your JSON. Type can be "enemy" or whatever other types you have.

Then just check the type on the way through the JSON and compare to the string "enemy" and only operate when that condition is true.

Like:
Code: Select all
{
type: "enemy",
name: "jabi-jabi",
stats: {
  attack: 22
  defense: 42
}
}
https://www.ravenheart.ca/home
I don't check the forums much anymore, but I will receive an email for PMs.

"Someone once told me I bite off more than I can chew...

I told them I would rather choke on greatness than nibble on mediocrity."
B
23
S
6
G
1
Posts: 1,419
Reputation: 4,857

Post » Tue Oct 27, 2015 6:16 pm

gumshoe2029 wrote:You should add a "type" tag to your JSON. Type can be "enemy" or whatever other types you have.

Then just check the type on the way through the JSON and compare to the string "enemy" and only operate when that condition is true.

Like:
Code: Select all
{
type: "enemy",
name: "jabi-jabi",
stats: {
  attack: 22
  defense: 42
}
}


Thanks for the tip. I already figured out a workaround, in case anyone is curious:

Since my enemies exist on a tilemap, I loop through the tilemap and pop the JSON of each enemy on to the back of my array when exporting a level. On import, I loop through the tiles again, creating an enemy depending on what tile it hits and activate an event group that contains an "On enemy created" event, so each time an enemy is created at a tile, it loads the first object JSON in the array and removes it. Since I loop through the tiles in the same order on import and export, the order of the JSON objects is always consistent when importing back in.
B
14
S
2
Posts: 73
Reputation: 794

Post » Wed Oct 28, 2015 7:00 pm

Workarounds are good too.
https://www.ravenheart.ca/home
I don't check the forums much anymore, but I will receive an email for PMs.

"Someone once told me I bite off more than I can chew...

I told them I would rather choke on greatness than nibble on mediocrity."
B
23
S
6
G
1
Posts: 1,419
Reputation: 4,857


Return to How do I....?

Who is online

Users browsing this forum: dop2000 and 5 guests