Introduction to the Realm SDK for Unity3D
Rate this announcement
In this video, Dominic Frei, iOS engineer on the Realm team, will introduce you to the Realm SDK for Unity3D. He will be showing you how to integrate and use the SDK based on a Unity example created during the video so that you can follow along.
The video is separated into the following sections:
- What is Realm and where to download it?
- Creating an example project
- Adding Realm to your project
- Executing simple CRUD operations
- Recap / Summary
Introduction to the Realm SDK for Unity3D
For those of you who prefer to read, below we have a full transcript of the video too. Please be aware that this is verbatim and it might not be sufficient to understand everything without the supporting video.
Hello and welcome to a new tutorial! Today we're not talking about playing games but rather how to make them. More specifically: how to use the Realm SDK to persist your data in Unity. I will show you where to download Realm, how to add it to your project and how to write the necessary code to save and load your data. Let's get started!
Realm is an open-source, cross-platform database available for many different platforms. Since we will be working with Unity we'll be using the Realm .NET SDK. This is not yet available through the Unity package manager so we need to download it from the Github repository directly. I will put a link to it into the description. When you go to Releases you can find the latest release right on the top of the page. Within the assets you'll find two Unity files. Make sure to choose the file that says 'unity.bundle' and download it.
Before we actually start integrating Realm into our Unity project let's create a small example. I'll be creating it from scratch so that you can follow along all the way and see how easy it is to integrate Realm into your project. We will be using the Unity Editor version 2021.2.0a10. We need to use this alpha version because there is a bug in the current Unity LTS version preventing Realm from working properly. I'll give it a name and choose a 2D template for this example.
We won't be doing much in the Unity Editor itself, most of the example will take place in code. All we need to do here is to add a Square object. The Square will change its color when we click on it and - as soon as we add Realm to the project - the color will be persisted to the database and loaded again when we start the game again. The square needs to be clickable, therefore we need to add a collider. I will choose a 'Box Collider 2D' in this case. Finally we'll add a script to the square, call it 'Square' and open the script.
The first thing we're going to do before we actually implement the square's behaviour is to add another class which will hold our data, the color of our square. We'll call this 'ColorEntity'. All we need for now are three properties for the colors red, green and blue. They will be of type float to match the UnityEngine's color properties and we'll default them to 0, giving us an initial black color. Back in the Square MonoBehaviour I'll add a ColorEntity property since we'll need that in several locations. During the Awake of the Square we'll create a new ColorEntity instance and then set the color of the square to this newly created ColorEntity by accessing it's SpriteRenderer and setting it's color. When we go back to the Unity Editor and enter Play Mode we'll see a black square.
Ok, let's add the color change. Since we added a collider to the square we can use the OnMouseDown event to listen for mouse clicks. All we want to do here is to assign three random values to our ColorEntity. We'll use Random.Range and clamp it between 0 and 1. Finally we need to update the square with these colors. To avoid duplicated code I'll grab the line from Awake where we set the color and put it in it's own function. Now we just call it in Awake and after every mouse click. Let's have a look at the result.
Initially we get our default black color. And with every click the color changes. When I stop and start again, we'll of course end up with the initial default again since the color is not yet saved. Let's do that next!
We go to Window, Package Manager. From here we click on the plus icon and choose 'Add package from tarball'. Now you just have to choose the tarball downloaded earlier. Keep in mind that Unity does not import the package and save it within your project but uses exactly this file wherever it is. If you move it, your project won't work anymore. I recommend moving this file from your Downloads to the project folder first. As soon as it is imported you should see it in the Custom section of your package list. That's all we need to do in the Unity Editor, let's get back to Visual Studio.
Let's start with our ColorEntity. First, we want to import the Realm package by adding 'using Realms'. The way Realm knows which objects are meant to be saved in the database is by subclassing 'RealmObjects'. That's all we have to do here really. To make our life a little bit easier though I'll also add some more things. First, we want to have a primary key by which we can later find the object we're looking for easily. We'll just use the 'ObjectName' for that and add an attribute on top of it, called 'PrimaryKey'. Next we add a default initialiser to create a new Realm object for this class and a convenience initialiser that sets the ObjectName right away. Ok, back to our Square. We need to import Realm here as well. Then we'll create a property for the Realm itself. This will later let us access our database. And all we need to do to get access to it is to instantiate it. We'll do this during awake as well, since it only needs to be done once.
Now that we're done setting up our Realm we can go ahead and look at how to perform some simple CRUD operations. First, we want to actually create the object in the database. We do this by calling add. Notice that I have put this into a block that is passed to the write function. We need to do this to tell our Realm that we are about to change data. If another process was changing data at the same time we could end up in a corrupt database. The write function makes sure that every other process is blocked from writing to the database at the time we're performing this change.
Another thing I'd like to add is a check if the ColorEntity we just created already exists. If so, we don't need to create it again and in fact can't since primary keys have to be unique. We do this by asking our Realm for the ColorEntity we're looking for, identified by it's primary key. I'll just call it 'square' for now. Now I check if the object could be found and only if not, we'll be creating it with exactly the same primary key. Whenever we update the color and therefore update the properties of our ColorEntity we change data in our database. Therefore we also need to wrap our mouse click within a write block. Let's see how that looks in Unity. When we start the game we still see the initial black state. We can still randomly update the color by clicking on the square. And when we stop and start Play Mode again, we see the color persists now.
Let's quickly recap what we've done. We added the Realm package in Unity and imported it in our script. We added the superclass RealmObject to our class that's supposed to be saved. And then all we need to do is to make sure we always start a write transaction when we're changing data. Notice that we did not need any transaction to actually read the data down here in the SetColor function.
Alright, that's it for this tutorial. I hope you've learned how to use Realm in your Unity project to save and load data.
News & Announcements
Realm Cocoa 5.0 - Multithreading Support with Integration for SwiftUI & Combine
Oct 19, 2022