Database Interactions in Unity

This week I will be taking a walk through the mysteries of using JSON received from a webserver to populate data and objects in Unity. Seems like a simple enough task but it turns out there are some very specific limitations that make this a bit more difficult than using JSON on just a “normal” website.

The First Hurdle

In the beginning, Unity did not support serializing or deserializing JSON natively. C# specific or Unity asset store plugins were required to accomplish tasks with JSON. Luckily for us, Unity has since added a native JSON api which makes things much simpler. However, there is one very big, giant caveat to this JSON api. It can not handle JSON arrays by default. It wants one piece of JSON and no more. So of course handling multiple rows of data received from our database becomes a problem. We simply can’t afford to make a separate call for each individual database row we need to access. But not to worry, the amazing community on Stackoverflow already came to the rescue with a neat little wrapper class to allow handling of JSON arrays.

The Second Hurdle

Now that we could receive and use our JSON data we needed to figure out how to map this info to usable Unity objects. In order to map the JSON data to a Unity class, the class must be serializable. No problem, except classes that inherit from MonoBehavior can not be serializable due to some behind the scenes serializing that already happens and would cause a conflict (as far as I can figure, that part is still a bit of a mystery). However, we can get around this by creating a serializable data class which is then passed to the original class. So for any classes that require data from the database, we must separate out the data and feed it into the original class to then instantiate them as GameObjects and use them in the actual game. This creates another layer of separation between game objects but keeps things fairly simple overall.

I did not expect that working with JSON would be such a large hurdle in the development process. However, now that the limitations have been addressed we can safely move forward with implementing even more database interactions in our game.

Leave a comment

Your email address will not be published. Required fields are marked *