HomeLearnHow-toPersistence in Unity Using Realm

Persistence in Unity Using Realm

Updated: Oct 19, 2021 |

Published: Oct 14, 2021

  • Realm
  • Atlas
  • C#
  • ...

By Dominic Frei

Rate this article

#Persistence in Unity using Realm


When creating a game with Unity, we often reach the point where we need to save data that we need at a later point in time. This could be something simple, like a table of high scores, or a lot more complex, like the state of the game that got paused and now needs to be resumed exactly the way the user left it when they quit it earlier. Maybe you have tried this before using PlayerPrefs but your data was too complex to save it in there. Or you have tried SQL only to find it to be very complicated and cumbersome to use.

Realm can help you achieve this easily and quickly with just some minor adjustments to your code.

The goal of this article is to show you how to add Realm to your Unity game and make sure your data is persisted. The Realm Unity SDK is part of our Realm .NET SDK. The documentation for the Realm .NET SDK will help you get started easily.

The first part of this tutorial will describe the example itself. If you are already familiar with Unity or really just want to see Realm in action, you can also skip it and jump straight to the second part.

#Example game

We will be using a simple 3D chess game for demonstration purposes. Creating this game itself will not be part of this tutorial. However, this section will provide you with an overview so that you can follow along and add Realm to the game. This example can be found in our Unity examples repository.

The final implementation of the game including the usage of Realm is also part of the example repository.


To make it easy to find your way around this example, here are some notes to get you started:

The interesting part in the MainScene to look at is the Board which is made up of Squares and Pieces. The Squares are just slightly scaled and colored default Cube objects which we utilize to visualize the Board but also detect clicks for moving Pieces by using its already attached Box Collider component.


The Pieces have to be activated first, which happens by making them clickable as well. Pieces are not initially added to the Board but instead will be spawned by the PieceSpawner. You can find them in the Prefabs folder in the Project hierarchy.


The important part to look for here is the Piece script which detects clicks on this Piece (3) and offers a color change via Select() (1) and Deselect() (2) to visualize if a Piece is active or not.

1using UnityEngine;
3public class Piece : MonoBehaviour
5 private Events events = default;
6 private readonly Color selectedColor = new Color(1, 0, 0, 1);
7 private readonly Color deselectedColor = new Color(1, 1, 1, 1);
9 // 1
10 public void Select()
11 {
12 gameObject.GetComponent<Renderer>().material.color = selectedColor;
13 }
15 // 2
16 public void Deselect()
17 {
18 gameObject.GetComponent<Renderer>().material.color = deselectedColor;
19 }
21 // 3
22 private void OnMouseDown()
23 {
24 events.PieceClickedEvent.Invoke(this);
25 }
27 private void Awake()
28 {
29 events = FindObjectOfType<Events>();
30 }

We use two events to actually track the click on a Piece (1) or a Square (2):

1using UnityEngine;
2using UnityEngine.Events;
4public class PieceClickedEvent : UnityEvent<Piece> { }
5public class SquareClickedEvent : UnityEvent<Vector3> { }
7public class Events : MonoBehaviour
9 // 1
10 public readonly PieceClickedEvent PieceClickedEvent = new PieceClickedEvent();
11 // 2
12 public readonly SquareClickedEvent SquareClickedEvent = new SquareClickedEvent();

The InputListener waits for those events to be invoked and will then notify other parts of our game about those updates. Pieces need to be selected when clicked (1) and deselected if another one was clicked (2).

Clicking a Square while a Piece is selected will send a message (3) to the GameState to update the position of this Piece.

1using UnityEngine;
3public class InputListener : MonoBehaviour
5 [SerializeField] private Events events = default;
6 [SerializeField] private GameState gameState = default;
8 private Piece activePiece = default;
10 private void OnEnable()
11 {
12 events.PieceClickedEvent.AddListener(OnPieceClicked);
13 events.SquareClickedEvent.AddListener(OnSquareClicked);
14 }
16 private void OnDisable()
17 {
18 events.PieceClickedEvent.RemoveListener(OnPieceClicked);
19 events.SquareClickedEvent.RemoveListener(OnSquareClicked);
20 }
22 private void OnPieceClicked(Piece piece)
23 {
24 if (activePiece != null)
25 {
26 // 2
27 activePiece.Deselect();
28 }
29 // 1
30 activePiece = piece;
31 activePiece.Select();
32 }
34 private void OnSquareClicked(Vector3 position)
35 {
36 if (activePiece != null)
37 {
38 // 3
39 gameState.MovePiece(activePiece, position);
40 activePiece.Deselect();
41 activePiece = null;
42 }
43 }

The actual movement as well as controlling the spawning and destroying of pieces is done by the GameState, in which all the above information eventually comes together to update Piece positions and possibly destroy other Piece objects. Whenever we move a Piece (1), we not only update its position (2) but also need to check if there is a Piece in that position already (3) and if so, destroy it (4).

In addition to updating the game while it is running, the GameState offers two more functionalities:

  • set up the initial board (5)
  • reset the board to its initial state (6)
1using System.Linq;
2using UnityEngine;
4public class GameState : MonoBehaviour
6 [SerializeField] private PieceSpawner pieceSpawner = default;
7 [SerializeField] private GameObject pieces = default;
9 // 1
10 public void MovePiece(Piece movedPiece, Vector3 newPosition)
11 {
12 // 3
13 // Check if there is already a piece at the new position and if so, destroy it.
14 var attackedPiece = FindPiece(newPosition);
15 if (attackedPiece != null)
16 {
17 // 4
18 Destroy(attackedPiece.gameObject);
19 }
21 // 2
22 // Update the movedPiece's GameObject.
23 movedPiece.transform.position = newPosition;
24 }
26 // 6
27 public void ResetGame()
28 {
29 // Destroy all GameObjects.
30 foreach (var piece in pieces.GetComponentsInChildren<Piece>())
31 {
32 Destroy(piece.gameObject);
33 }
35 // Recreate the GameObjects.
36 pieceSpawner.CreateGameObjects(pieces);
37 }
39 private void Awake()
40 {
41 // 5
42 pieceSpawner.CreateGameObjects(pieces);
43 }
45 private Piece FindPiece(Vector3 position)
46 {
47 return pieces.GetComponentsInChildren<Piece>()
48 .FirstOrDefault(piece => piece.transform.position == position);
49 }

Go ahead and try it out yourself if you like. You can play around with the board and pieces and reset if you want to start all over again.

To make sure the example is not overly complex and easy to follow, there are no rules implemented. You can move the pieces however you want. Also, the game is purely local for now and will be expanded using our Sync component in a later article to be playable online with others.

In the following section, I will explain how to make sure that the current game state gets saved and the players can resume the game at any state.

Adding Realm to your project

The first thing we need to do is to import the Realm framework into Unity. The easiest way to do this is by using NPM.

You'll find it via WindowsPackage Manager → cogwheel in the top right corner → Advanced Project Settings:


Within the Scoped Registries, you can add the Name, URL, and Scope as follows:


This adds NPM as a source for libraries. The final step is to tell the project which dependencies to actually integrate into the project. This is done in the manifest.json file which is located in the Packages folder of your project.

Here you need to add the following line to the dependencies:

1"io.realm.unity": "<version-number>"

Replace <version-number> with the most recent Realm version found in https://github.com/realm/realm-dotnet/releases and you're all set.

The final manifest.json should look something like this:

2 "dependencies": {
3 ...
4 "io.realm.unity": "10.3.0"
5 },
6 "scopedRegistries": [
7 {
8 "name": "NPM",
9 "url": "https://registry.npmjs.org/",
10 "scopes": [
11 "io.realm.unity"
12 ]
13 }
14 ]

When you switch back to Unity, it will reload the dependencies. If you then open the Package Manager again, you should see Realm as a new entry in the list on the left:


We can now start using Realm in our Unity project.

#Top-down or bottom-up?

Before we actually start adding Realm to our code, we need to think about how we want to achieve this and how the UI and database will interact with each other.

There are basically two options we can choose from: top-down or bottom-up.

The top-down approach would be to have the UI drive the changes. The Piece would know about its database object and whenever a Piece is moved, it would also update the database with its new position.

The preferred approach would be bottom-up, though. Changes will be applied to the Realm and it will then take care of whatever implications this has on the UI by sending notifications.

Let's first look into the initial setup of the board.

#Setting up the board

The first thing we want to do is to define a Realm representation of our piece since we cannot save the MonoBehaviour directly in Realm. Classes that are supposed to be saved in Realm need to subclass RealmObject. The class PieceEntity will represent such an object. Note that we cannot just duplicate the types from Piece since not all of them can be saved in Realm, like Vector3 and enum.

Add the following scripts to the project:

1using Realms;
2using UnityEngine;
4public class PieceEntity : RealmObject
6 // 1
7 public PieceType PieceType
8 {
9 get => (PieceType)Type;
10 private set => Type = (int)value;
11 }
13 // 2
14 public Vector3 Position
15 {
16 get => PositionEntity.ToVector3();
17 set => PositionEntity = new Vector3Entity(value);
18 }
20 // 3
21 private int Type { get; set; }
22 private Vector3Entity PositionEntity { get; set; }
24 // 4
25 public PieceEntity(PieceType type, Vector3 position)
26 {
27 PieceType = type;
28 Position = position;
29 }
31 // 5
32 protected override void OnPropertyChanged(string propertyName)
33 {
34 if (propertyName == nameof(PositionEntity))
35 {
36 RaisePropertyChanged(nameof(Position));
37 }
38 }
40 // 6
41 private PieceEntity()
42 {
43 }
1using Realms;
2using UnityEngine;
4public class Vector3Entity : EmbeddedObject // 7
6 public float X { get; private set; }
7 public float Y { get; private set; }
8 public float Z { get; private set; }
10 public Vector3Entity(Vector3 vector) // 8
11 {
12 X = vector.x;
13 Y = vector.y;
14 Z = vector.z;
15 }
17 public Vector3 ToVector3() => new Vector3(X, Y, Z); // 9
19 private Vector3Entity() // 10
20 {
21 }

Even though we cannot save the PieceType (1) and the position (2) directly in the Realm, we can still expose them using backing variables (3) to make working with this class easier while still fulfilling the requirements for saving data in Realm.

Additionally, we provide a convenience constructor (4) for setting those two properties. A default constructor (6) also has to be provided for every RealmObject. Since we are not going to use it here, though, we can set it to private.

Note that one of these backing variables is a RealmObject itself, or rather a subclass of it: EmbeddedObject (7). By extracting the position to a separate class Vector3Entity the PieceEntity is more readable. Another plus is that we can use the EmbeddedObject to represent a 1:1 relationship. Every PieceEntity can only have one Vector3Entity and even more importantly, every Vector3Entity can only belong to one PieceEntity because there can only ever be one Piece on any given Square.

The Vector3Entity, like the PieceEntity, has some convenience functionality like a constructor that takes a Vector3 (8), the ToVector3() function (9) and the private, mandatory default constructor (10) like PieceEntity.

Looking back at the PieceEntity, you will notice one more function: OnPropertyChanged (5). Realm sends notifications for changes to fields saved in the database. Since we expose those fields using PieceType and Position, we need to make sure those notifications are passed on. This is achieved by calling RaisePropertyChanged(nameof(Position)); whenever PositionEntity changes.

The next step is to add some way to actually add Pieces to the Realm. The current database state will always represent the current state of the board. When we create a new PieceEntity—for example, when setting up the board—the GameObject for it (Piece) will be created. If a Piece gets moved, the PieceEntity will be updated by the GameState which then leads to the Piece's GameObject being updated using above mentioned notifications.

First, we will need to set up the board. To achieve this using the bottom-up approach, we adjust the PieceSpawner as follows:

1using Realms;
2using UnityEngine;
4public class PieceSpawner : MonoBehaviour
6 [SerializeField] private Piece prefabBlackBishop = default;
7 [SerializeField] private Piece prefabBlackKing = default;
8 [SerializeField] private Piece prefabBlackKnight = default;
9 [SerializeField] private Piece prefabBlackPawn = default;
10 [SerializeField] private Piece prefabBlackQueen = default;
11 [SerializeField] private Piece prefabBlackRook = default;
13 [SerializeField] private Piece prefabWhiteBishop = default;
14 [SerializeField] private Piece prefabWhiteKing = default;
15 [SerializeField] private Piece prefabWhiteKnight = default;
16 [SerializeField] private Piece prefabWhitePawn = default;
17 [SerializeField] private Piece prefabWhiteQueen = default;
18 [SerializeField] private Piece prefabWhiteRook = default;
20 public void CreateNewBoard(Realm realm)
21 {
22 realm.Write(() =>
23 {
24 // 1
25 realm.RemoveAll<PieceEntity>();
27 // 2
28 realm.Add(new PieceEntity(PieceType.WhiteRook, new Vector3(1, 0, 1)));
29 realm.Add(new PieceEntity(PieceType.WhiteKnight, new Vector3(2, 0, 1)));
30 realm.Add(new PieceEntity(PieceType.WhiteBishop, new Vector3(3, 0, 1)));
31 realm.Add(new PieceEntity(PieceType.WhiteQueen, new Vector3(4, 0, 1)));
32 realm.Add(new PieceEntity(PieceType.WhiteKing, new Vector3(5, 0, 1)));
33 realm.Add(new PieceEntity(PieceType.WhiteBishop, new Vector3(6, 0, 1)));
34 realm.Add(new PieceEntity(PieceType.WhiteKnight, new Vector3(7, 0, 1)));
35 realm.Add(new PieceEntity(PieceType.WhiteRook, new Vector3(8, 0, 1)));
37 realm.Add(new PieceEntity(PieceType.WhitePawn, new Vector3(1, 0, 2)));
38 realm.Add(new PieceEntity(PieceType.WhitePawn, new Vector3(2, 0, 2)));
39 realm.Add(new PieceEntity(PieceType.WhitePawn, new Vector3(3, 0, 2)));
40 realm.Add(new PieceEntity(PieceType.WhitePawn, new Vector3(4, 0, 2)));
41 realm.Add(new PieceEntity(PieceType.WhitePawn, new Vector3(5, 0, 2)));
42 realm.Add(new PieceEntity(PieceType.WhitePawn, new Vector3(6, 0, 2)));
43 realm.Add(new PieceEntity(PieceType.WhitePawn, new Vector3(7, 0, 2)));
44 realm.Add(new PieceEntity(PieceType.WhitePawn, new Vector3(8, 0, 2)));
46 realm.Add(new PieceEntity(PieceType.BlackPawn, new Vector3(1, 0, 7)));
47 realm.Add(new PieceEntity(PieceType.BlackPawn, new Vector3(2, 0, 7)));
48 realm.Add(new PieceEntity(PieceType.BlackPawn, new Vector3(3, 0, 7)));
49 realm.Add(new PieceEntity(PieceType.BlackPawn, new Vector3(4, 0, 7)));
50 realm.Add(new PieceEntity(PieceType.BlackPawn, new Vector3(5, 0, 7)));
51 realm.Add(new PieceEntity(PieceType.BlackPawn, new Vector3(6, 0, 7)));
52 realm.Add(new PieceEntity(PieceType.BlackPawn, new Vector3(7, 0, 7)));
53 realm.Add(new PieceEntity(PieceType.BlackPawn, new Vector3(8, 0, 7)));
55 realm.Add(new PieceEntity(PieceType.BlackRook, new Vector3(1, 0, 8)));
56 realm.Add(new PieceEntity(PieceType.BlackKnight, new Vector3(2, 0, 8)));
57 realm.Add(new PieceEntity(PieceType.BlackBishop, new Vector3(3, 0, 8)));
58 realm.Add(new PieceEntity(PieceType.BlackQueen, new Vector3(4, 0, 8)));
59 realm.Add(new PieceEntity(PieceType.BlackKing, new Vector3(5, 0, 8)));
60 realm.Add(new PieceEntity(PieceType.BlackBishop, new Vector3(6, 0, 8)));
61 realm.Add(new PieceEntity(PieceType.BlackKnight, new Vector3(7, 0, 8)));
62 realm.Add(new PieceEntity(PieceType.BlackRook, new Vector3(8, 0, 8)));
63 });
64 }
66 public void SpawnPiece(PieceEntity pieceEntity, GameObject parent)
67 {
68 var piecePrefab = pieceEntity.PieceType switch
69 {
70 PieceType.BlackBishop => prefabBlackBishop,
71 PieceType.BlackKing => prefabBlackKing,
72 PieceType.BlackKnight => prefabBlackKnight,
73 PieceType.BlackPawn => prefabBlackPawn,
74 PieceType.BlackQueen => prefabBlackQueen,
75 PieceType.BlackRook => prefabBlackRook,
76 PieceType.WhiteBishop => prefabWhiteBishop,
77 PieceType.WhiteKing => prefabWhiteKing,
78 PieceType.WhiteKnight => prefabWhiteKnight,
79 PieceType.WhitePawn => prefabWhitePawn,
80 PieceType.WhiteQueen => prefabWhiteQueen,
81 PieceType.WhiteRook => prefabWhiteRook,
82 _ => throw new System.Exception("Invalid piece type.")
83 };
85 var piece = Instantiate(piecePrefab, pieceEntity.Position, Quaternion.identity, parent.transform);
86 piece.Entity = pieceEntity;
87 }

The important change here is CreateNewBoard. Instead of spawning the Pieces, we now add PieceEntity objects to the Realm. When we look at the changes in GameState, we will see how this actually creates a Piece per PieceEntity.

Here we just wipe the database (1) and then add new PieceEntity objects (2). Note that this is wrapped by a realm.write block. Whenever we want to change the database, we need to enclose it in a write transaction. This makes sure that no other piece of code can change the database at the same time since transactions block each other.

The last step to create a new board is to update the GameState to make use of the new PieceSpawner and the PieceEntity that we just created.

We'll go through these changes step by step. First we also need to import Realm here as well:

1using Realms;

Then we add a private field to save our Realm instance to avoid creating it over and over again. We also create another private field to save the collection of pieces that are on the board and a notification token which we need for above mentioned notifications:

1private Realm realm;
2private IQueryable<PieceEntity> pieceEntities;
3private IDisposable notificationToken;

In Awake, we do need to get access to the Realm. This is achieved by opening an instance of it (1) and then asking it for all PieceEntity objects currently saved using realm.All (2) and assigning them to our pieceEntities field:

1private void Awake()
3 realm = Realm.GetInstance(); // 1
4 pieceEntities = realm.All<PieceEntity>(); // 2
6 // 3
7 notificationToken = pieceEntities.SubscribeForNotifications((sender, changes, error) =>
8 {
9 // 4
10 if (error != null)
11 {
12 Debug.Log(error.ToString());
13 return;
14 }
16 // 5
17 // Initial notification
18 if (changes == null)
19 {
20 // Check if we actually have `PieceEntity` objects in our Realm (which means we resume a game).
21 if (sender.Count > 0)
22 {
23 // 6
24 // Each `RealmObject` needs a corresponding `GameObject` to represent it.
25 foreach (PieceEntity pieceEntity in sender)
26 {
27 pieceSpawner.SpawnPiece(pieceEntity, pieces);
28 }
29 }
30 else
31 {
32 // 7
33 // No game was saved, create a new board.
34 pieceSpawner.CreateNewBoard(realm);
35 }
36 return;
37 }
39 // 8
40 foreach (var index in changes.InsertedIndices)
41 {
42 var pieceEntity = sender[index];
43 pieceSpawner.SpawnPiece(pieceEntity, pieces);
44 }
45 });

Note that collections are live objects. This has two positive implications: Every access to the object reference always returns an updated representation of said object. Because of this, every subsequent change to the object will be visible any time the object is accessed again. We also get notifications for those changes if we subscribed to them. This can be done by calling SubscribeForNotifications on a collection (3).

Apart from an error object that we need to check (4), we also receive the changes and the sender (the updated collection itself) with every notification. For every new collection of objects, an initial notification is sent that does not include any changes but gives us the opportunity to do some initial setup work (5).

In case we resume a game, we'll already see PieceEntity objects in the database even for the initial notification. We need to spawn one Piece per PieceEntity to represent it (6). We make use of the SpawnPiece function in PieceSpawner to achieve this. In case the database does not have any objects yet, we need to create the board from scratch (7). Here we use the CreateNewBoard function we added earlier to the PieceSpawner.

On top of the initial notification, we also expect to receive a notification every time a PieceEntity is inserted into the Realm. This is where we continue the CreateNewBoard functionality we started in the PieceSpawner by adding new objects to the database. After those changes happen, we end up with changes (8) inside the notifications. Now we need to iterate over all new PieceEntity objects in the sender (which represents the pieceEntities collection) and add a Piece for each new PieceEntity to the board.

Apart from inserting new pieces when the board gets set up, we also need to take care of movement and pieces attacking each other. This will be explained in the next section.

#Updating the position of a PieceEntity

Whenever we receive a click on a Square and therefore call MovePiece in GameState, we need to update the PieceEntity instead of directly moving the corresponding GameObject. The movement of the Piece will then happen via the PropertyChanged notifications as we saw earlier.

1public void MovePiece(Vector3 oldPosition, Vector3 newPosition)
3 realm.Write(() =>
4 {
5 // 1
6 var attackedPiece = FindPieceEntity(newPosition);
7 if (attackedPiece != null)
8 {
9 realm.Remove(attackedPiece);
10 }
12 // 2
13 var movedPieceEntity = FindPieceEntity(oldPosition);
14 movedPieceEntity.Position = newPosition;
15 });
18// 3
19private PieceEntity FindPieceEntity(Vector3 position)
21 return pieceEntities
22 .Filter("PositionEntity.X == $0 && PositionEntity.Y == $1 && PositionEntity.Z == $2",
23 position.x, position.y, position.z)
24 .FirstOrDefault();

Before actually moving the PieceEntity, we do need to check if there is already a PieceEntity at the desired position and if so, destroy it. To find a PieceEntity at the newPosition and also to find the PieceEntity that needs to be moved from oldPosition to newPosition, we can use queries on the pieceEntities collection (3).

By querying the collection (calling Filter), we can look for one or multiple RealmObjects with specific characteristics. In this case, we're interested in the RealmObject that represents the Piece we are looking for. Note that when using a Filter we can only filter using the Realm properties saved in the database, not the exposed properties (Position and PieceType) exposed for convenience by the PieceEntity.

If there is an attackedPiece at the target position, we need to delete the corresponding PieceEntity for this GameObject (1). After the attackedPiece is updated, we can then also update the movedPiece (2).

Like the initial setup of the board, this has to be called within a write transaction to make sure no other code is changing the database at the same time.

This is all we had to do to update and persist the position. Go ahead and start the game. Stop and start it again and you should now see the state being persisted.

#Resetting the board

The final step will be to also update our ResetGame button to update (or rather, wipe) the Realm. At the moment, it does not update the state in the database and just recreates the GameObjects.

Resetting works similar to what we do in Awake in case there were no entries in the database—for example, when starting the game for the first time.

We can reuse the CreateNewBoard functionality here since it includes wiping the database before actually re-creating it:

1public void ResetGame()
3 pieceSpawner.CreateNewBoard(realm);

With this change, our game is finished and fully functional using a local Realm to save the game's state.

#Recap and conclusion

In this tutorial, we have seen that saving your game and resuming it later can be easily achieved by using Realm.

The steps we needed to take:

  • Add Realm via NPM as a dependency.
  • Import Realm in any class that wants to use it by calling using Realms;.
  • Create a new Realm instance via Realm.GetInstance() to get access to the database.
  • Define entites by subclassing RealmObject (or any of its subclasses):

    • Fields need to be public and primitive values or lists.
    • A default constructor is mandatory.
    • A convenience constructor and additional functions can be defined.
  • Write to a Realm using realm.Write() to avoid data corruption.
  • CRUD operations (need to use a write transaction):

    • Use realm.Add() to Create a new object.
    • Use realm.Remove() to Delete an object.
    • Read and Update can be achieved by simply getting and setting the public fields.

With this, you should be ready to use Realm in your games.

If you have questions, please head to our developer community website where the MongoDB engineers and the MongoDB community will help you build your next big idea with MongoDB and Realm.

Rate this article
© 2021 MongoDB, Inc.


  • Careers
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.