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
Against the Tide
Tower Defense + Match 3
Status | In development |
Author | Against the Tide |
Genre | Strategy |
Tags | Fantasy, Level Editor, match3, Mouse only, realtime, Real time strategy, Singleplayer, Tower Defense |
Languages | English |
More posts
- New game page layoutJan 24, 2021
- 0.150.0 Released & DiscordJan 15, 2021
- 0.100.0 released!Jan 14, 2021
- It's awhile, but I'm still working!Jan 10, 2021
- Almost done with loadoutsJan 02, 2021
- Working on the loadout screensJan 02, 2021
- Take a screenshot in unity (with transparent background)Dec 31, 2020
- Finally! Play and upload levels online!Dec 30, 2020
- How to implement "wait at least this long" in Unity/C#Dec 28, 2020
- Level Editor is live!Dec 27, 2020
Leave a comment
Log in with itch.io to leave a comment.