# 5. Spawning Pooling and Ownership
Part of [[Netcode for GameObjects Deep Dive]]. Previous: [[4. RPCs Directions and Server Validation]]. Next: [[6. Movement Authority Owner vs Server]].
## 5.1 Spawning rules
- In client-server, only the **server** spawns NetworkObjects. Clients ask by RPC.
- The prefab must be in the NetworkManager's **Network Prefabs** list, on every build.
- `Spawn()` makes the server the owner. `SpawnWithOwnership(clientId)` gives it to a client.
- `Despawn(true)` destroys the object everywhere. `Despawn(false)` despawns it but leaves the GameObject, which is what a pool wants.
## 5.2 Pooling networked objects
Pooling with plain `SetActive` breaks with networking, because clients still Instantiate and Destroy their copies. NGO's answer is a **prefab handler**: register an `INetworkPrefabInstanceHandler` for a prefab, and NGO calls *your* `Instantiate` and `Destroy` on every peer, server and clients alike. That's the [[Object Pooling and Spawners]] pattern applied on every machine.
```csharp
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
/// <summary>
/// Reuses NetworkObjects instead of Instantiate/Destroy. Registering a handler with
/// NetworkManager.PrefabHandler makes NGO call Instantiate/Destroy here on EVERY peer,
/// so clients pool too. Register on all peers before spawning (OnNetworkSpawn of a scene object is fine).
/// </summary>
public sealed class NetworkObjectPool : NetworkBehaviour
{
[SerializeField] List<GameObject> prefabs = new List<GameObject>();
[SerializeField] int prewarm = 8;
readonly Dictionary<GameObject, Handler> _handlers = new Dictionary<GameObject, Handler>();
public static NetworkObjectPool Instance { get; private set; }
sealed class Handler : INetworkPrefabInstanceHandler
{
readonly GameObject _prefab;
readonly Transform _parent;
readonly Stack<NetworkObject> _free = new Stack<NetworkObject>();
public Handler(GameObject prefab, Transform parent) { _prefab = prefab; _parent = parent; }
public void Prewarm(int count)
{
for (var i = 0; i < count; i++)
{
var go = Object.Instantiate(_prefab, _parent);
go.SetActive(false);
_free.Push(go.GetComponent<NetworkObject>());
}
}
public NetworkObject Instantiate(ulong ownerClientId, Vector3 position, Quaternion rotation)
{
var no = _free.Count > 0 ? _free.Pop() : Object.Instantiate(_prefab, _parent).GetComponent<NetworkObject>();
no.transform.SetPositionAndRotation(position, rotation);
no.gameObject.SetActive(true);
return no;
}
public void Destroy(NetworkObject networkObject)
{
networkObject.gameObject.SetActive(false);
_free.Push(networkObject);
}
public void Clear()
{
while (_free.Count > 0)
{
var no = _free.Pop();
if (no != null) Object.Destroy(no.gameObject);
}
}
}
public override void OnNetworkSpawn()
{
Instance = this;
foreach (var prefab in prefabs)
{
var h = new Handler(prefab, transform);
h.Prewarm(prewarm);
_handlers[prefab] = h;
NetworkManager.PrefabHandler.AddHandler(prefab, h);
}
}
public override void OnNetworkDespawn()
{
foreach (var kv in _handlers)
{
NetworkManager.PrefabHandler.RemoveHandler(kv.Key);
kv.Value.Clear();
}
_handlers.Clear();
if (Instance == this) Instance = null;
}
/// <summary>Server only: spawn a pooled instance for everyone.</summary>
public NetworkObject ServerSpawn(GameObject prefab, Vector3 position, Quaternion rotation, ulong owner = NetworkManager.ServerClientId)
{
if (!IsServer) return null;
var no = _handlers[prefab].Instantiate(owner, position, rotation);
no.SpawnWithOwnership(owner, destroyWithScene: true);
return no;
}
/// <summary>Server only. Despawn(false) hands the object back to the handler instead of destroying it.</summary>
public static void ServerDespawn(NetworkObject no)
{
if (no != null && no.IsSpawned) no.Despawn(false);
}
}
```
Put it on a scene NetworkObject (so it spawns on every peer and registers the handlers there), list your enemy and pickup prefabs, and spawn with `NetworkObjectPool.Instance.ServerSpawn(prefab, pos, rot)`. Prefabs still have to be in the Network Prefabs list.
## 5.3 Ownership
The owner of a NetworkObject is the peer whose input drives it. Owner-authoritative components (an owner-mode `NetworkTransform`, owner-write NetworkVariables) follow ownership automatically. Change it on the server with `ChangeOwnership(clientId)`, and give it back with `RemoveOwnership()`.
In **Distributed Authority** there's no server to decide, so ownership rules live on the object:
- `OwnershipStatus.Distributable`: may be handed to another client when its owner leaves.
- `Transferable`: other clients may take it.
- `RequestRequired`: they must ask with `RequestOwnership()`, and the owner's `OnOwnershipRequested` callback decides.
```csharp
using Unity.Netcode;
using Unity.Netcode.Components;
using UnityEngine;
/// <summary>
/// Ownership in both topologies. Client-server: the server hands ownership to the carrier
/// (ChangeOwnership) and takes it back on drop. Distributed Authority: there is no server, so the
/// crate is Transferable with RequestRequired, and the current owner approves requests.
/// An owner-authoritative NetworkTransform means the carrier moves it with zero lag.
/// </summary>
[RequireComponent(typeof(NetworkTransform))]
public sealed class CarryableCrate : NetworkInteractable
{
public readonly NetworkVariable<ulong> Carrier = new NetworkVariable<ulong>(ulong.MaxValue,
NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public bool IsCarried => Carrier.Value != ulong.MaxValue;
void Awake() => GetComponent<NetworkTransform>().AuthorityMode = NetworkTransform.AuthorityModes.Owner;
public override void OnNetworkSpawn()
{
if (NetworkManager.DistributedAuthorityMode)
{
NetworkObject.SetOwnershipStatus(NetworkObject.OwnershipStatus.Transferable | NetworkObject.OwnershipStatus.RequestRequired);
NetworkObject.OnOwnershipRequested = clientId => !IsCarried; // owner says no while someone holds it
}
}
// Client-server path, called by Interactor on the server.
public override void ServerInteract(ulong clientId)
{
if (IsCarried && Carrier.Value != clientId) return;
if (IsCarried) { NetworkObject.RemoveOwnership(); SetCarrierRpc(ulong.MaxValue); return; } // drop: back to the server
NetworkObject.ChangeOwnership(clientId);
SetCarrierRpc(clientId);
}
// Carrier is owner-written, so the server tells the new owner to write it.
[Rpc(SendTo.Owner)]
void SetCarrierRpc(ulong clientId) => Carrier.Value = clientId;
// Distributed Authority path, called locally by the player who wants it.
public void RequestPickUp()
{
if (!NetworkManager.DistributedAuthorityMode) return;
if (IsOwner) { Carrier.Value = NetworkManager.LocalClientId; return; }
var status = NetworkObject.RequestOwnership();
if (status != NetworkObject.OwnershipRequestStatus.RequestSent)
Debug.Log(
quot;[Crate] request not sent: {status}");
}
public override void OnGainedOwnership()
{
if (NetworkManager.DistributedAuthorityMode) Carrier.Value = NetworkManager.LocalClientId;
}
}
```
**Untested ordering.** In the client-server path, the server changes ownership and then sends `SetCarrierRpc` to the new owner. This assumes the ownership change reaches the client before the RPC. If you see "not owner" warnings on `Carrier`, make `Carrier` server-write in client-server and owner-write only in DA.
## Exercises
1. Pool a "coin" prefab and spawn 200 of them. Compare Profiler GC allocation with and without the handler.
2. In DA, have two players grab the same crate at the same time. Who gets it, and why?