Course contentsShow
← Unity Game Development
Lesson 787 of 82812. Multiplayer and DeploymentFree lesson

Managing Networked Object Spawning Lifecycle

Control the dynamic creation and destruction of networked entities during gameplay to ensure all clients stay synchronized with the current world state.

In this lesson, you will learn how to orchestrate the lifecycle of dynamic objects to ensure that every player sees the same entities at the same time without causing state desynchronization.

The Networked Lifecycle

When you spawn an object like a projectile, an item pickup, or an enemy in a networked environment, you cannot simply use Instantiate(). Because the server is the source of truth, it must initiate the spawn process so the NetworkManager can assign a unique NetworkObjectId to the entity. Once the server spawns an object, the networking library automatically replicates that object to all connected clients, ensuring they all instantiate their own local representation of the same entity.

Orchestrating Spawns

The lifecycle is governed by the server. If a client attempts to "spawn" an object, they must send a request to the server, which then verifies the request and executes the spawn.

public void SpawnNetworkObject(GameObject prefab)
{
    // Ensure we are on the server before spawning
    if (!IsServer) return;

    GameObject instance = Instantiate(prefab);
    NetworkObject netObj = instance.GetComponent<NetworkObject>();
    
    // Spawn() registers the object with the network system
    netObj.Spawn();
}

Managing Destruction

Lifecycle management also requires disciplined destruction. If a player picks up an item, you cannot simply call Destroy(gameObject). If a client destroys an object locally without server authority, that object will still exist on the server and other clients, leading to a "ghost" object.

Instead, you must call netObj.Despawn(). When the server calls Despawn(), it notifies all connected clients that the object is no longer part of the current state, and the network system cleans up the instances across the entire session. This ensures the world state remains consistent and prevents orphaned objects from consuming memory or processing power. Always remember: if the server spawns it, the server must be the one to despawn it to keep the clients in perfect lockstep.

Key Takeaway: To maintain a synchronized world state, always handle entity instantiation and destruction through server-side commands, ensuring every client receives the authoritative signal to create or remove an object.