How to import a JSON file in my game and read it?

I’m trying to create a wave system in my android game. I want to write JSON files containing the representation of waves in each level. I want the JSON to be packed with the game. Can I do this? Is there a better way to do this?

Use a TextAsset to store the json in your project: Unity - Scripting API: TextAsset

Then use the JsonUtility to read the string: Unity - Scripting API: JsonUtility.FromJson

2 Likes

An alternative to JSON would be constructing ScriptableObjects to define the key parts of each of your waves, then constructing containers that list all the pieces that go into each wave. This has the upside of letting you directly reference assets in the game, meaning you don’t need to read a string saying “Enemy17Flying” and then go dig up the proper prefab for such an enemy. You would just use that enemy by reference.

If you go the JSON route, everything that GroZZ says above is spot-on, but be sure you aware of the severe limitations of the built-in JSON system.

In general I highly suggest staying away from Unity’s JSON “tiny lite” package. It’s really not very capable at all and will silently fail on very common data structures, such as Dictionaries and Hashes and ALL properties.

Instead grab Newtonsoft JSON .NET off the asset store for free, or else install it from the Unity Package Manager (Window → Package Manager).

https://forum.unity.com/threads/jso…-not-working-as-expected.722783/#post-4824743

https://assetstore.unity.com/packages/tools/input-management/json-net-for-unity-11347

Also, always be sure to leverage sites like:

https://jsonlint.com
https://json2csharp.com
https://csharp2json.io

PS: for folks howling about how NewtonSoft JSON .NET will “add too much size” to your game, JSON .NET is like 307k in size, and it has the important advantage that it actually works the way you expect a JSON serializer to work in the year 2021.

2 Likes

Thank you for your reply, what containers do you mean?

I meant any type of ScriptableObject that might contain either just a list of the parts going into a wave, or when you get bold, contain a timeline-driven list, eg., at t+10 seconds, three enemy appear, etc.

The important part about using ScriptableObjects is that they are first class citizens in the Unity Editor, letting you effectively extend the power of the Unity Editor to become a custom editor for your game.

1 Like