# Instantiate and Destroy Objects

coherence makes it easy to instantiate networked objects. If you instantiate a [networked Prefab](#user-content-fn-1)[^1] while the game is running, it **automatically instantiates** on all connected clients. You don't need to do anything else to make it happen.

However some rules apply, so read on to understand more about the process.

### How do I specify a Prefab to spawn for the player?

It is important to understand that coherence has no concept of a "player Prefab" that maps 1:1 with each Client. Clients can control only one network entity, multiple, or none at all.

Clients can also trade authority over them at runtime. For example, a Client might initially have authority over a character, which can then move to another Client during gameplay.

It's **up to you** to decide what constitutes a "player Prefab": you can instantiate one before connecting, right after connection, or at any point during the simulation. You can even just leave it in the scene, and let each player bring a copy of that into the simulation (in this case, make sure the Prefab is not set to be [unique](https://docs.coherence.io/1.5/manual/lifetime/uniqueness)!).

Finally, if you come from other networking frameworks, you might expect a player Prefab to be be instantiated by the network manager (in coherence, the [CoherenceBridge](https://docs.coherence.io/1.5/manual/components/coherence-bridge)), but that is not the case. Like all other network entities, it can be **instantiated by any script**.

{% hint style="info" %}
**Identifying Clients**

You do have the ability to assign a Prefab to each client: the [ClientConnection Prefab](https://docs.coherence.io/1.5/client-connections#clientconnection-objects). This lives and dies with the client's connection, and you can use it to hold important data related to that Client. You can assign it in the Inspector of the [CoherenceBridge](https://docs.coherence.io/1.5/manual/components/coherence-bridge).

ClientConnection Prefabs are **optional**.
{% endhint %}

## Instantiating entities

You can instantiate a networked Prefab in the following ways:

* Use `GameObject.Instantiate()`, and provide a reference to the Prefab:

```csharp
GameObject newGameObject = Instantiate(prefab);
```

* Simply include the Prefab in a scene.
* (Editor only, for testing) Drag the Prefab from the Project window to the scene or to the Hierarchy while the game is running.

In all of these cases, the Prefab will be immediately instantiated on all other connected clients and Simulators.

Just ensure to include a CoherenceSync component on the Prefab, and that netcode is [baked](https://docs.coherence.io/1.5/manual/baking-and-code-generation) correctly.

### Who gets authority?

Whoever instantiates a Prefab gets full [authority](https://docs.coherence.io/1.5/manual/authority) over it. All other clients will see it as remote.

{% hint style="info" %}
The value of the **Simulate In** property on the CoherenceSync can modify this behaviour. Read more about [authority models](https://docs.coherence.io/sdk-1.4/manual/authority#authority-models).
{% endhint %}

### Instantiate objects for other clients

You cannot directly instantiate an entity owned by another Client. The Client that instantiates a Prefab automatically has authority over it.

However, you can transfer authority immediately after instantiation. In code:

```csharp
// Instantiates a Prefab and immediately gives authority away
public void SpawnAndTransfer(GameObject prefab, ClientID recipientID)
{
        GameObject newGameObject = Instantiate(prefab);
        newGameObject.GetComponent<CoherenceSync>().TransferAuthority(recipientID);
}
```

(to get other clients' IDs you need to have [ClientConnections](https://docs.coherence.io/1.5/manual/client-connections) enabled)

{% hint style="success" %}
This is a perfectly valid strategy to have a Simulator spawn player characters for connected Clients.
{% endhint %}

## Destroying entities

To destroy a networked Prefab, simply invoke `GameObject.Destroy()` on it. coherence will **automatically destroy all remote copies**.

Keep in mind is that only whoever has State authority over it can destroy an entity. If someone else does it, they will get a warning in the console.

### Destroying other player's entities

Clients cannot directly destroy entities they don't have authority over. Instead, you may:

* Send a [Network Command](https://docs.coherence.io/1.5/manual/networking-state-changes/commands) to **ask the owner to destroy it**. In code:

```csharp
private void DestroyNetworkEntity(GameObject objectToRemove)
{
    CoherenceSync sync = objectToRemove.GetComponent<CoherenceSync>();
    
    if (sync.HasStateAuthority)
    {
        // If we have authority, no need to send a command
        Destroy(objectToRemove);
    }
    else
    {
        // Change MyBehaviour here to whatever type will receive the Command
        sync.SendCommand<MyBehaviour>(nameof(MyBehaviour.RemoveObject),
                                            MessageTarget.AuthorityOnly);
    }
}
```

```csharp
// The command invoked on the receiving end
[Command]
public void RemoveObject()
{
    Destroy(this.gameObject);
}
```

* **Take authority over the entity first**, then destroy it locally. This is slightly slower as it implies a full roundtrip (request > response > destruction), but it's a viable option if the requester needs to verify whether the entity can be destroyed at all. You can implement the conditions under which the other client will [approve or deny the request](https://docs.coherence.io/1.5/authority/authority-transfer#requesting-authority-in-code). In code:

```csharp
private void RequestDestroy(GameObject objectToRemove)
{
    CoherenceSync sync = objectToRemove.GetComponent<CoherenceSync>();
    
    if (sync.HasStateAuthority)
    {
        Destroy(objectToRemove);
    }
    else
    {
        // Listen to authority transfer
        sync.OnStateAuthority.AddListener(() => Destroy(objectToRemove));
        
        sync.RequestAuthority(AuthorityType.Full);
    }
}
```

Note that we're assuming that the request above always succeeds, and we're not implementing any approval/denial code for the sake of simplicity.

## Customise instantiation and destruction

In coherence, you can take full control of how network entities are instantiated.

A typical use for custom instantiation is streaming assets in with the [**Addressables package**](https://docs.unity3d.com/Packages/com.unity.addressables@latest), which coherence is fully integrated with. Another typical use case is [object pooling](#object-pooling).

To use custom instantiation you can't just hard reference the Prefab and invoke `Instantiate()` or `Destroy()` as described above. Instead, you have to [use its CoherenceSyncConfig](https://docs.coherence.io/1.5/manual/asset-management/using-coherencesyncconfig-to-instantiate-gameobjects) to let the chosen instantiator script take over and perform custom operations.

## Object pooling

We natively support object pooling, so that newly requested entities don't just get created from scratch, but they are taken from a pre-existing pool.

#### How to use object pooling

In the CoherenceSync component inspector, you will find an option called **Instantiate Via**.

Select the option called *Pool*, and define the initial and max size of the pool:

<figure><img src="https://6468334-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FBuIORmlspPFsVrlyahy9%2Fuploads%2Fgit-blob-85a51a4d39ba2bb9c9360bca0be648a3e38d0b75%2FPooledNetworkEntity_Inspector.png?alt=media" alt="" width="563"><figcaption><p>A CoherenceSync for which the Pool instantiator has been selected</p></figcaption></figure>

When the game starts, coherence will automatically create a pool of disabled instances of this Prefab in the DontDestroyOnLoad scene. It will then activate these for new **remote entities** that use this Prefab that other clients created.

If you want to take from the same pooling system to instantiate your own **local/authoritative entities**, you can do so by using the [CoherenceSyncConfig asset](https://docs.coherence.io/1.5/asset-management#coherencesyncconfig-assets) corresponding to your Prefab. If you reference this asset, you will be able to [instantiate and destroy entities by using its API](https://docs.coherence.io/1.5/manual/asset-management/using-coherencesyncconfig-to-instantiate-gameobjects): these methods will use the underlying pool implementation to do so.

When remote entities are removed or go out of a [LiveQuery](https://docs.coherence.io/1.5/manual/optimization/areas-of-interest), they will be automatically deactivated and move back into the pool.

#### Use your pre-existing object pooling system

If you already have a pooling system in place (even a third-party asset!) and you would like remote objects to leverage it, you can hook your own pool into a custom instantiator using the `INetworkObjectInstantiator` interface. This is described in the [Instantiate Via page](https://docs.coherence.io/1.5/asset-management/instantiate-via#creating-your-own-instantiator).

[^1]: A Prefab that has a CoherenceSync component.
