Spawning and Despawning Items
Learn about spawning and despawning by having your players throw cubes around!
Last updated
Learn about spawning and despawning by having your players throw cubes around!
Last updated
Now that we have players moving around, let's learn how to spawn and despawn .
While you can and regular Game Objects, Network Objects need to be Spawned and Despawned, this tells FishNet to synchronize the action over the network. FishNet stores all network object prefabs in a collection called the . You can see this and customize it on the .
We have added a large green cube to act as the floor which you can do too, but this isn't a vital step.
Let's create a Cube in the scene hierarchy, and add a NetworkObject component to it. We've also decreased it's scale by half so that it doesn't look too large. Then drag it into the project window to turn it into a prefab; you can destroy the original game object in the scene hierarchy now.
Now create a script called PlayerCubeCreator
and add it to your Player Prefab. This script is going to be responsible for spawning our new cube item across the network.
Because this script contains a ServerRpc, it will also need to be a NetworkBehaviour. The Update
method listens for the user to press the Fire1 button (typically the left mouse button) and then calls SpawnCube
.
Understanding SpawnCube
:
The ServerRpc attribute: This is crucial. It means this method is intended to be called by a client, but it will execute only on the server. The client sends a message to the server, requesting this method to be run.
Spawn(obj);
: This is the most critical line for networked objects. Calling Spawn(obj)
on the NetworkObject
tells FishNet's ServerManager
to "spawn" this object over the network. This means the server will now instruct all currently connected clients (and any clients that connect later) to instantiate their own replica of this object.
If you launch the game now, the cubes should have basics physics working.
You may notice the cubes' positions don't always sync up after they are moved around, that's because we haven't done any positional syncing besides the initial position syncing that FishNet automatically did when we called Spawn
.
Now that we can Spawn
cubes successfully, let's Despawn
them after a few seconds so that we don't end up with too many objects at once.
Create a new script called DespawnAfterTime
:
This script uses the NetworkBehaviour override method to start a Coroutine which will Despawn
the object. OnStartServer will run on the server when the object is initialized with the network.
Despawn
needs to be called on the server and it will destroy the game object locally as well as on all clients automatically for you.