Jörn Alexander Quent's notebook

where I share semi-interesting stuff from my work

How you can easily load data into Unity3D using a .JSON file

In this post, I quickly show a way to load data into Unity3D using a simple .json file. Note there are other & for the most part simpler ways if you use UXF - Unity Experiment Framework, which provide a way to parse on data via .json out of the box. However, the problem is that this only works if you already started the experiment and some people who might stumble on this don’t even know what I am talking about. Anyway in my case, I want to provide information to Unity3D before I started my UXF session. In fact as I will show in my next post, I wan to control the text of the UXF start up panel itself using a .json file so I can easily switch between an English & a Chinese version of a research task that I created.

All the code & the example file can be found in this folder of my Unity script repo on GitHub.

Now, let me show you how you can read & use a simple .json file like this:

{
    "var1": " Hello World!",
    "var2": 1.0
}

The file has two variables called var1 & var2. Step 1: In order to access them we have to create a custom class like this

[System.Serializable]
public class JSONDataClass {
    	public string var1;
    	public float var2;
    }

that has the same variable names as the .json file. Note if there is mismatch between the file and your class you might get an error. After that we can use a function like this

    /// <summary>
    /// Method to read in a JSON file that is placed in the StreamingAssets folder. 
    /// </summary>
    void GetDataFromJSON(string fileName){
    	// Get path
        string path2file = Path.GetFullPath(Path.Combine(Application.streamingAssetsPath, fileName));

        // Get JSON input
        var sr = new StreamReader(path2file);
        var fileContents = sr.ReadToEnd();
        sr.Close();

        // Get instruction data profile
        JSONData = JsonUtility.FromJson<JSONDataClass>(fileContents);
    }

to read the file and so you can easily get the data by running everything inside the start function. For instance, like this:

    // Start is called before the first frame update
    void Start(){
    	// Get the Startup Text from the JSON file
    	GetDataFromJSON(JSON_fileName);

    	// Show that it worked
        Debug.Log(JSONData.var1);
        Debug.Log(JSONData.var2);
    	
    }

And voila we can now use the values inside the file and print them to the console.

The whole script can be found here. I hope this is useful to anyone as it took my while to get this one working for me.


Share