The most concise method (I know) of loading a JSON file asynchronously in Unity/C#


Loading code from the Resources folder is bad. Don't do it. But so is eating a dozen chocolate chip cookies. The cookies are delicious and the Resources folder is a quick, dirty way to get dynamic data into your system before you can justify the trouble of AssetBundles and other forms of better data management.

The following code is the shortest, cleanest form (I know) for loading a JSON file from the Resources folder. As a bonus, the Game.Load.File method can be used to load any file in the folder. I'm not going to explain how to structure your C# Class to parse your JSON into an object. There's plenty of blog posts about that already. This is focusing on wrapping away the annoying bits into a clean, two-line format you can reuse.

YourCode.cs

using System;
using System.Collections;
using UnityEngine;
public class YourGameComponent : MonoBehaviour {
    IEnumerator Start() {
        Data data = null;
        yield return Game.Load.Json<Data>("path/to/your/game/file", d => data = d);
        // do stuff with data
    }
}

Game.cs

using System;
using System.Collections;
using UnityEngine;
namespace Game {
    public static class Load {
        public static IEnumerator Json<t>(string path, Action<t> callback) {
            ResourceRequest request = null;
            yield return File(path, r => request = r);
            
            TextAsset textAsset = (TextAsset) request.asset;
            callback(JsonUtility.FromJson<t>(textAsset.text));
        }
        public static IEnumerator File(string path, Action<ResourceRequest> callback) {
            ResourceRequest request = Resources.LoadAsync<UnityEngine.Object>(path);
            yield return new WaitUntil(() => request.isDone);
            if (request.asset == null) {
                throw new Exception($"File doesn't exist: {path}");
            }
            callback(request);
        }
    }
}

Get Against the Tide

Download NowName your own price

Leave a comment

Log in with itch.io to leave a comment.