Fish-Net: Networking Evolved
  • Overview
    • What is FishNet?
      • Features
        • Unity Compatibility
        • Performance
          • Benchmark Setup
          • Fish-Networking Vs Mirror
      • Pro, Projects, and Support
      • Business Support
      • Development
        • Changelog
        • Roadmap
      • Branding
      • Legal Restrictions
    • Showcase
      • Upcoming Releases
    • Asset Integrations
      • Fish-Network-Discovery
    • Community Resources
  • Guides
    • Getting Started
      • Installing Fish-Networking
      • Getting Connected
      • Preparing Your Player
      • Moving Your Player Around
      • Spawning and Despawning Items
      • Using SyncVars to Sync Colors
      • Connecting to Remote Devices
      • Beyond the Basics
    • High-Level Overview
      • Fundamentals
      • Networking Models
      • Terminology
        • Server, Client, Host
        • Communicating
        • Miscellaneous
      • Transports
    • Features
      • Server and Client Identification
        • Executing on Server or Client
        • NetworkConnections
      • Networked GameObjects and Scripts
        • NetworkObjects
        • NetworkBehaviour
        • Spawning and Despawning
          • Predicted Spawning
          • Nested NetworkObjects
          • Object Pooling
      • Network State Events
      • Network Communication
        • Remote Procedure Calls
        • SyncTypes
          • Customizing Behavior
          • SyncVar
          • SyncList
          • SyncHashSet
          • SyncDictionary
          • SyncTimer
          • SyncStopwatch
          • Custom SyncType
        • Broadcasts
      • Data Serialization
        • Custom Serializers
          • Interface Serializers
          • Inheritance Serializers
      • Ownership
        • Using Ownership To Read Values
      • Area of Interest (Observer System)
        • Modifying Conditions
        • Custom Conditions
      • Scene Management
        • Scene Events
        • Scene Data
          • SceneLookupData
          • SceneLoadData
          • SceneUnloadData
        • Loading Scenes
          • Automatic Online and Offline Scenes
        • Unloading Scenes
        • Scene Stacking
        • Scene Caching
        • Scene Visibility
        • Persisting NetworkObjects
        • Custom Scene Processors
          • Addressables
      • InstanceFinder
      • Addressables
      • Transports
        • Multipass
      • Prediction
        • What Is Client-Side Prediction
        • Configuring PredictionManager
        • Configuring TimeManager
        • Configuring NetworkObject
        • Offline Rigidbodies
        • Interpolations
        • Creating Code
          • Controlling An Object
          • Non-Controlled Object
          • Understanding ReplicateState
            • Using States In Code
            • Predicting States In Code
          • Advanced Controls
        • Custom Comparers
        • PredictionRigidbody
        • Using NetworkColliders
      • Lag Compensation
        • States
        • Raycast
        • Projectiles
    • Upgrading API
    • Server Hosting
      • Edgegap - Official Partner
        • Getting Started with Edgegap
      • Hathora
        • Getting Started with Hathora
      • Amazon Web Services (AWS)
        • Getting Started with AWS
    • Upgrading To Fish-Networking
    • Troubleshooting
      • Technical Limitations
      • Creating Bug Reports
        • Report Example
      • FAQ
  • FishNet Building Blocks
    • Components
      • Managers
        • NetworkManager
        • TimeManager
        • PredictionManager
        • ServerManager
        • ClientManager
        • SceneManager
        • TransportManager
          • IntermediateLayer
        • StatisticsManager
        • ObserverManager
          • HashGrid
        • RollbackManager (Pro Feature)
      • Prediction
        • Network Collider
          • NetworkCollision
          • NetworkCollision2D
          • NetworkTrigger
          • NetworkTrigger2D
        • OfflineRigidbody
        • PredictedOwner
        • PredictedSpawn
      • Utilities
        • PingDisplay
        • BandwidthDisplay
        • Tick Smoothers
          • NetworkTickSmoother
          • OfflineTickSmoother
          • MonoTickSmoother [Obsolete]
          • DetachableNetworkTickSmoother [Obsolete]
      • PlayerSpawner
      • DefaultScene
      • ServerSpawner
      • Authenticator
      • ColliderRollback
      • NetworkAnimator
      • NetworkBehaviour
      • NetworkTransform
      • NetworkObject
      • NetworkObserver
    • Prefabs
      • NetworkManager
      • NetworkHudCanvas
    • ScriptableObjects
      • ObserverConditions
        • DistanceCondition
        • GridCondition
        • HostOnlyCondition
        • MatchCondition
        • OwnerOnlyCondition
        • SceneCondition
      • SpawnablePrefabs
        • DefaultPrefabObjects
        • SinglePrefabObjects
        • DualPrefabObjects
      • LevelLoggingConfiguration
    • Transports
      • Tugboat
      • Multipass
      • Yak (Pro Feature)
      • Bayou
      • FishyWebRTC
      • FishyUnityTransport
      • FishySteamworks (Steam)
      • FishyEOS (Epic Online Services)
      • FishyFacepunch (Steam)
      • FishyRealtime (Photon)
  • API Documentation
    • API Reference
Powered by GitBook
On this page
  1. Guides
  2. Getting Started

Spawning and Despawning Items

Learn about spawning and despawning by having your players throw cubes around!

PreviousMoving Your Player AroundNextUsing SyncVars to Sync Colors

Last updated 1 day ago

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.

1

Creating the Item NetworkObject Prefab

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.

2

Creating a Script to Spawn the Cube

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.

PlayerCubeCreator.cs
using FishNet.Object;
using UnityEngine;

public class PlayerCubeCreator : NetworkBehaviour
{
    public NetworkObject cubePrefab;

    void Update()
    {
        // Only the local player object should perform these actions.
        if (!IsOwner)
            return;

        if (Input.GetButtonDown("Fire1"))
            SpawnCube();
    }

    // We are using a ServerRpc here because the Server needs to do all network object spawning.
    [ServerRpc]
    private void SpawnCube()
    {
        NetworkObject obj = Instantiate(cubePrefab, transform.position, Quaternion.identity);
        Spawn(obj); // NetworkBehaviour shortcut for ServerManager.Spawn(obj);
    }
}
PlayerCubeCreator.cs
using FishNet.Object;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerCubeCreator : NetworkBehaviour
{
    public NetworkObject cubePrefab;

    public override void OnStartClient()
    {
        if (IsOwner)
            GetComponent<PlayerInput>().enabled = true;
    }

    public void OnFire(InputAction.CallbackContext context)
    {
        if (context.started)
            SpawnCube();
    }

    // We are using a ServerRpc here because the Server needs to do all network object spawning.
    [ServerRpc]
    private void SpawnCube()
    {
        NetworkObject obj = Instantiate(cubePrefab, transform.position, Quaternion.identity);
        Spawn(obj); // NetworkBehaviour shortcut for ServerManager.Spawn(obj);
    }
}

Because this script contains a , it will also need to be a .

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.

3

Assigning the Prefab to Your Script

Now select your Player Prefab and assign your Cube Prefab to the "Cube Prefab" field in your newly created Player Cube Creator script.

You may have noticed that an Empty Network Behaviour component was automatically added to your game objects with a NetworkObject component. This happens because each FishNet requires every NetworkObject to also have a NetworkBehaviour on it, and it will automatically add an empty one if it doesn't detect any. You can safely remove this empty component as you have added multiple other NetworkBehaviour components, but it's not a problem either way.

4

Test If the Spawning Works

Now launch a couple instances of your game and see if you can run around and spawn cube items by pressing the Fire1 button. The cubes should be visible on all devices connected to each other.

5

Add Some Physics

Static cubes are boring! Let's add a Rigidbody component to the Cube Prefab to enable basic physics interactions with them.

Now the cubes should roll around and collide with the ground. Let's add a Rigidbody to the Player now and set it to Is Kinematic.

6

Test If the Physics Works

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.

Networked Rigidbodies are a complex topic, and better suited to a different guide, but if you want to test a really basic setup up, you can add a to your Cube Prefab and set its Component Configuration to Rigidbody.

7

Script to Despawn Cubes On A Timer

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:

DespawnAfterTime.cs
using FishNet.Object;
using System.Collections;
using UnityEngine;

public class DespawnAfterTime : NetworkBehaviour
{
    public float secondsBeforeDespawn = 3f;

    public override void OnStartServer()
    {
        StartCoroutine(DespawnAfterSeconds());
    }

    private IEnumerator DespawnAfterSeconds()
    {
        yield return new WaitForSeconds(secondsBeforeDespawn);

        Despawn(); // NetworkBehaviour shortcut for ServerManager.Despawn(gameObject);
    }
}

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.

8

Assigning the Script and Testing

Open your Cube Prefab now and add the Despawn After Time script you just made to the object.

Launch the game again and observe the objects being Despawned successfully on the server and all clients after a few seconds.

Download the project files with these completed steps here, or explore the repository:

Source Files Repository

NetworkObjects
Instantiate
Destroy
Spawnable Prefabs
NetworkManager
NetworkBehaviour
NetworkTransform
OnStartServer
ServerRpc
The Cube with size adjusted and NetworkObject added
Player Cube Creator with Cube Prefab assigned
Player Spawning Cubes
Rigidbody added to the Cube
Player with Kinematic Rigidbody added
Players Spawning Physics Cubes
Cubes Despawning After 3 Seconds
An image of a Cube Game Object set to half scale and with a NetworkObject component added.