Custom instantiation and destruction

Topics covered

Object lifecycle | Custom instantiators | Runtime Unique IDs

In many cases, creating and destroying GameObjects like usual will be enough. Just call Instantiate() or Destroy(), and coherence takes care of instantiating and destroying the appropriate Prefab instance on each connected Client.

However, there are moments when it makes sense to customize how exactly coherence does this. To take full control over the lifetime of the object, or to attach custom behavior to these events.

coherence provides different object instantiators by default (and we use the Pool Instantiator one too), but for ultimate control we also have the ability to create new, completely custom ones.

Our use case

The campsite in this demo has a few pre-placed unique objects in the scene, that can be picked up, moved, and burned on the campfire.

Until the Keeper Robot comes in and recreates them, they will not be replaced.

When we burn them, we could in theory just destroy the instance. However the burn code is deeply nested in the Burnable.cs class which is used not only by these unique objects, but also by the pooled and non-unique wood logs.

In this method we do this:

private IEnumerator GetBurned()
{
    // ...
    _sync.ReleaseInstance();
}

A simple ReleaseInstance() does the trick for the logs which are non-unique objects. They just go back into the object pool.

However, by default unique network entities also get disabled, not destroyed. This doesn't work for our special objects!

If you're curious about this code, you can check out the file in the coherence package folder in 📁io.coherence.sdk/Coherence.Toolkit/CoherenceSyncConfigs/ObjectInstantiators and open DefaultInstantiator.cs

We could potentially add an if statement in the GetBurned() above, detect if the object being destroyed is a log or not, and act differently based on that. Or subclass the Burnable and implement overrides for GetBurned...

... or we can just create a custom instantiator, and take full control of the object's lifecycle. Let's see the code.

The custom instantiator

Creating a custom instantiator is trivial. We just need a class to implement the interface INetworkObjectInstantiator, like so:

[Serializable, DisplayName("UniqueBurnableObjects", "Custom instantiator [...]")]
public class UniqueBurnableInstantiator : INetworkObjectInstantiator
{
    // OnUniqueObjectReplaced() does nothing
    
    public ICoherenceSync Instantiate(CoherenceBridge bridge,
                        ICoherenceSync prefab, Vector3 position, Quaternion rotation)
    {
        return Object.Instantiate(prefab as MonoBehaviour,
                                position, rotation) as ICoherenceSync;
    }
    
    public void Destroy(ICoherenceSync obj)
    {
        var monoBehaviour = obj as MonoBehaviour;
        Object.Destroy(monoBehaviour.gameObject);
    }
    
    // WarmUpInstantiator() does nothing
    // OnApplicationQuit() does nothing
}

The key parts of this script being that on network entity creation a simple Object.Instantiate() is performed, and on release Object.Destroy(). The other methods (omitted here) are actually empty.

We also want to prepend the class with the DisplayName attribute so it shows up in the dropdown when we configure a CoherenceSync. Now the UniqueBurnableObjects instantiator appears alongside the others in the Instantiate via dropdown:

That's it, the instantiator is ready to use.

When we call ReleaseInstance() now, it will act differently depending on which instantiator the Prefab is configured to use: the wood logs get disabled, but the unique campfire objects get destroyed.

This was a very simple use case for customization, but it illustrates how easy it can be to get in control of the lifetime of Prefab instances associated to network entities.

API Reference for INetworkObjectInstantiator can be found here.

Object anchors

The first time these special unique objects come online, they spawn a persistent invisible object we call "object anchor". This object holds the original position and rotation of the object, so that the Keeper Robot can come in at a later time and put the recreated object back into its place. You could think of these objects as placeholders.

One interesting thing we do with anchors is that they are themselves unique objects, but because they are spawned at runtime, they need to get their unique ID dynamically at runtime.

The code is in the PersistentObject class:

private void SpawnAnchor()
{
    // Code simplified for clarity ...

    string uniqueID = _sync.ManualUniqueId;
    _bridge.UniquenessManager.RegisterUniqueId(uniqueID + "-anchor");
    objectAnchorSync = Instantiate(anchorPrefab,
                            transform.position, transform.rotation);
}

We take the ManualUniqueId from the object spawning it (i.e., "Boombox"), and we combine with the string "-anchor" to create a new unique ID, "Boombox-anchor". We register this ID to the UniquenessManager of the CoherenceBridge to inform it that the next spawned network entity will have that ID. And then we simply call Instantiate().

Because they are set to be Persistent, even though a player has burned something and disconnected, the anchors stay on the Replication Server. When a Simulator connects it will find these placeholders and, thanks to the synced properties, will know exactly what to recreate and where to put it.

The check code is in KeeperRobot.cs, under CheckAnchors() and ActOnAnchor().

First, each anchor's isObjectPresent property is used for a quick scan. This property is synced.

If the object is still present, the robot needs to get a reference to it. It calls GetLinkedObject() on the anchor, which does this:

public GameObject GetLinkedObject()
{
    UniqueObjectReplacement uor =
        _sync.CoherenceBridge.UniquenessManager.TryGetUniqueObject(holdingForUUID);
    bool found = uor.localObject != null;
    return found ? ((CoherenceSync)uor.localObject).gameObject : null;
}

Once again using the UUID of the object this anchor is a placeholder for (holdingForUUID) as a key, we can now ask the UniquenessManager to retrieve an object that has that UUID.

With a reference to this, the robot can now put it back into place using the anchor's position and rotation as a reference.

And if the object has been destroyed (isObjectPresent is false), the robot proceeds to recreate it.

private Transform RecreateObject(ObjectAnchor objAnchor)
{
    foreach (CoherenceSyncConfig config in configRegistry)
    {
        if (config.ID == objAnchor.syncConfigId)
        {
            _sync.CoherenceBridge.UniquenessManager.RegisterUniqueId(objAnchor.holdingForUUID);
            CoherenceSync newSync = config.GetInstance(holdSocket.position, holdSocket.rotation);
            // ...
        }
    }
    // ...
}

Using the anchor's syncConfigId as a key, it looks in the CoherenceSyncConfigRegistry and finds the archetype to recreate. This is similar to how we used the registry as a catalogue when dealing with the campfire object.

After that, like we saw before, the robot registers the newly recreated object with the UniquenessManager so that it has the same UUID that it had before being burned.

The object is reinstated, and to a new Client connecting, it will look exactly the same as if it never got removed.