User Tools

Site Tools


data_files

This is an old revision of the document!


Data Files


Although it should be considered an experimental feature at this time and requires a bit of manual setup, it's possible to access custom data stored in JSON files from scripts. To do so, you must first create a subfolder named “data” within your game's project folder and place the desired JSON file into that folder. When exporting your game, the editor will automatically include any files in the data folder having the .json extension.

As a simple example, let's say you wanted to maintain a list of items that the player character should begin the game with without needing to update your game's startup script every time the list changes. In this scenario, you could create a JSON file within the data folder named “start_items.json” that looks something like this, with an array of item IDs corresponding to the desired items.

[
   "ITEM_0001",
   "ITEM_0002",
   "ITEM_0003"
]

You can then use the “data” syntax to reference the filename (minus the .json extension) and access its data from a script. In our example, you could use this syntax along with a For loop to give each item to the player from your game's startup script.

for item_id in data["start_items"] do
   give_item(item_id)
end

Alternatively, each item in the list could be accessed using the array index syntax, or you could even randomly select one item from the list to give to the player.

for i in range(3) do
   give_item(data["start_items"][i])
end
give_item(data["start_items"][random(0, 2)])

This could be expanded further by also providing a count for each of the items. Instead of just a list of string values, the JSON file would have a list of objects, each having a key/value pair for the item ID and count.

[
   {
      "id": "ITEM_0001",
      "count": 2
   },
   {
      "id": "ITEM_0002",
      "count": 5
   }
]

Using the expanded JSON file containing counts for each item, the script below would give the player two of ITEM_0001 and five of ITEM_0002.

for item in data["start_items"] do
  give_item(item["id"], item["count"])
end

As another example, assume that we want to maintain a list of entity properties that will be assigned to a character at some point during the game. A file named “npc_properties.json” could be created in the data folder with the following contents (specifically an object with a set of key/value pairs as the root element).

{
   "visited": false
}

You could then loop through each of the key/value pairs and assign the value to a property on the entity.

for prop_name in data["npc_properties"] do
   set_entity_property(self, prop_name, data["props"][prop_name])
end
data_files.1588706697.txt.gz · Last modified: 2020/05/05 12:24 by justin