Loading JSON Files in Unity
Ashley Kwon (Spring 2023)
This tutorial shows how to access JSON files in a Unity project with a C# program. Before you begin this tutorial, you need to ensure the following:
Your JSON files are saved with the correct file format.
Your Unity project's Assets folder contains a folder titled "Resources". This Resources folder should be created by default when you make a new Unity project.
Go the Resources folder described above and create a new folder. Then, move your JSON files into this new folder. Please note that the function described below can only load one JSON file at a time.
Initiate a C# script that will load your JSON file.
In this C# script, use one of the default functions (Start and Update) or define your own function that loads your JSON file.
In that function, write the following line, which reads a JSON file from a folder titled "Json" and assigns the resulting string to a string variable named "json".
string json = Resources.Load<TextAsset>("Json/" + file name without .json);
The folder name "Json" can differ based on the name of the folder where you saved your JSON file. Also, please note that the JSON file name that follows the folder name should be a string without .json. For example, if I want to load a JSON file named data.json, then the file name that follows the folder name in the code above should be "data"
Attach the simple C# script you wrote to an object in your scene. This object can be a button, an empty object ... etc. If you want to load your JSON data when users open your scene without having to interact with anything, I recommend making an empty object and attaching the C# script to it. In this case, make sure the line from 4 is in one of the default functions (Start or Update). However, if you want to load the data upon certain user interactions, then attach the script to the object (e.g., a button) that users can interact with and write the line from 4 in the function that gets called only when the interactions happen.