Spawn Objects
ObjectNet allows to spawn objects over network, when those objects are spawned all network peers will be notified to spawn the same object.
Spawning on the Server
On the server (or host), you can spawn network objects using Unity's standard Instantiate()
method. ObjectNet's built-in detection system will automatically recognize when a NetworkObject is created and synchronize it across all connected clients. This makes it easy to use Unity’s native object creation workflow for networked objects.
Alternatively, you can use ObjectNet's dedicated NetworkGameObject.NetworkInstantiate()
method for similar results.
// Using Unity's Instantiate method
GameObject.Instantiate(this.prefabToSpawn, this.spawnPosition, Quaternion.identity);
// OR using ObjectNet's NetworkGameObject.Instantiate
NetworkGameObject.NetworkInstantiate(this.prefabToSpawn, this.spawnPosition, Quaternion.identity);
Both methods will ensure the object is created on all clients and properly synchronized.
Spawning on Clients
On clients, ObjectNet's automatic detection system does not apply. This means that simply using Unity’s Instantiate
method will only create the object locally and will not synchronize it with other clients.
To spawn an object across all clients from a non-server instance, you must use NetworkGameObject.NetworkInstantiate()
. This explicitly informs the server to handle the object creation and propagate it to all other connected clients.
// Using ObjectNet to spawn the object on all clients
NetworkGameObject.NetworkInstantiate(this.prefabToSpawn, this.spawnPosition, Quaternion.identity);
This ensures the object is properly created and synchronized across the network, regardless of whether the request originated from the server or a client.
Retrieveing GameObject Reference
When spawning a network object using ObjectNet, you can retrieve a reference to the instantiated GameObject. ObjectNet uses asynchronous operations to ensure the object is fully synchronized across the network before providing the reference.
You can use the await
keyword with the NetworkGameObject.Instantiate
method to get the spawned object. This guarantees that the reference is ready and fully initialized for use.
public async void SpawnGameObjectExample()//note the method need to be async
{
// Spawn the object and retrieve its reference asynchronously
GameObject spawnedObject = await NetworkGameObject.Instantiate(this.prefabToSpawn, this.spawnPosition, Quaternion.identity);
}
Using async/await with ObjectNet's NetworkGameObject.Instantiate
ensures that your code is efficient, reliable, and synchronized across the network.
FAQ:
Last updated