# Custom instantiation and destruction

#### **Topics covered**

Object lifecycle | [Custom instantiators](https://docs.coherence.io/1.3/manual/asset-management#creating-your-own-instantiator) | 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](https://docs.coherence.io/1.3/manual/asset-management#coherencesyncconfig-instantiate-via-option) by default (and we use [the Pool Instantiator](https://docs.coherence.io/1.3/getting-started/samples-and-tutorials/campfire-project/leveraging-object-pooling) 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](https://docs.coherence.io/1.3/getting-started/samples-and-tutorials/campfire-project/running-a-server-side-npc) comes in and recreates them, they will not be replaced.

<figure><img src="https://content.gitbook.com/content/NnpDkLUgRAbq6m09r93U/blobs/Y22a4t68B35m7xzAdClD/CampObjects.jpg" alt=""><figcaption><p>Some pre-placed objects: the boombox, the banjo, a bin</p></figcaption></figure>

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:

```csharp
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](https://docs.coherence.io/1.3/getting-started/samples-and-tutorials/campfire-project/leveraging-object-pooling).

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

{% hint style="info" %}
If you're curious about this code, you can check out the file in the coherence package folder in :file\_folder:`io.coherence.sdk/Coherence.Toolkit/CoherenceSyncConfigs/ObjectInstantiators` and open `DefaultInstantiator.cs`
{% endhint %}

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:

{% code fullWidth="false" %}

```csharp
[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
}
```

{% endcode %}

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:

<figure><img src="https://content.gitbook.com/content/NnpDkLUgRAbq6m09r93U/blobs/ea0iV0AgZ3Sj7JTeA7VX/BoomboxInstantiator.png" alt="" width="563"><figcaption></figcaption></figure>

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.

{% hint style="info" %}
API Reference for `INetworkObjectInstantiator` can be found [here](https://unityapi.coherence.io/docs/v1.0.0/api/Coherence.Toolkit.INetworkObjectInstantiator.html).
{% endhint %}

### 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](https://docs.coherence.io/1.3/getting-started/samples-and-tutorials/campfire-project/running-a-server-side-npc) can come in at a later time and put the recreated object back into its place. You could think of these objects as placeholders.

<div><figure><img src="https://content.gitbook.com/content/NnpDkLUgRAbq6m09r93U/blobs/5KzvgWBvXs7z7UVBqCB7/ObjectAnchors.png" alt=""><figcaption><p>The anchors, created in Play mode</p></figcaption></figure> <figure><img src="https://content.gitbook.com/content/NnpDkLUgRAbq6m09r93U/blobs/VajQ9lYKUGXS8GkHDNXG/ObjectAnchorInspector.png" alt=""><figcaption><p>The Inspector of an anchor holds information about the object it relates to</p></figcaption></figure></div>

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:

{% code fullWidth="false" %}

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

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

{% endcode %}

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:

```csharp
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.

```csharp
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](https://docs.coherence.io/1.3/getting-started/samples-and-tutorials/campfire-project/a-unique-object-with-complex-state).

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.
