Persistent Objects

Normcore’s rooms use a datastore which means that any state in the datastore can persist between sessions.

By default, all models are flagged to destroy when either the client that owns the model leaves, or when the last client leaves. However, this is an easy thing to change.

To start, open up one of the examples you’ve created, for this guide, I’m going to show you how to make both the CubeSync example from Synchronizing your own data, and the brush strokes from Creating a multiplayer drawing app, persistent.

First, let’s start with the CubeSync demo. You can download the sample code here.

This one is pretty easy. Find the RealtimeView on our Cube in the scene, open up Advanced Settings, and uncheck the “Destroy when owner or last client leaves” checkbox. That’s it!

Hit Play and changed the color of the cube using the ColorSyncTest component. Exit play mode, and hit Play again. Once the Unity editor connects to the room, the color of the cube is restored.

For the drawing app, adding persistence to the brush strokes isn’t much harder (you can download the project here. Inside of the Brush component, there’s a line where new BrushStroke prefabs are instantiated:

    Realtime.Instantiate(_brushStrokePrefab.name, ownedByClient: true, useInstance: _realtime);
  

To make BrushStroke prefabs persist between sessions, we can add destroyWhenOwnerOrLastClientLeaves: false when instantiating the object:

    Realtime.Instantiate(_brushStrokePrefab.name, ownedByClient: true, destroyWhenOwnerOrLastClientLeaves: false, useInstance: _realtime);
  

Done & done. Hit Play, draw a brush stroke, exit play mode, and then hit Play again. The brush stroke prefab is spawned and populated with the data stored in the datastore.

It’s worth noting that when you start to use persistent objects, it’s very important to follow the rules for property / component IDs. If you need to change a model, make sure never to reuse an existing ID or to change the type of an ID that was already in use. Doing so will break your application’s ability to interface with persistent models that were stored by previous versions of your application.