This document is about: FUSION 2-SHARED
SWITCH TO

4 - Car Spawning

Overview

Part 4 explains the logic for spawning a car for each player that joins. We will be converting the existing car to a prefab, adding the necessary Fusion components and creating a script to spawn it when necessary.

Creating the car prefab

Add a NetworkObject component to the Car. This component gives the object a network identity so that all peers can reference it.

Add a NetworkTransform component to it. NetworkTransform automatically synchronizes the position of the object to other clients.

Drag the Car into the Project window to create a prefab and delete it from the scene. With that the car is ready to be spawned.

Car Spawner

In a multiplayer game, you will often instantiate a character (or car) per player. Unlike in a single player project, instantiation is done with a special Runner.Spawn method which takes care of instantiating the prefab for everyone.

A good moment to spawn the car is when the client joined into a session. For that a custom script is needed. Create a CarSpawner script and open it. Add the following code to it:

C#

using Fusion;
using UnityEngine;

public class CarSpawner : SimulationBehaviour, IPlayerJoined
{
    public GameObject CarPrefab;

    public void PlayerJoined(PlayerRef player)
    {
        if (player == Runner.LocalPlayer)
        {
            Runner.Spawn(CarPrefab, new Vector3(0, 1, 0), Quaternion.identity);
        }
    }
}

The spawn code is very simple. Extending a SimulationBehaviour provides access to the NetworkRunner which contains all information about the current session including the player ID of the local player.

The IPlayerJoined interface has a PlayerJoined function which gets called whenever a player joins the session if the behaviour is on the same GameObject as the runner. This happens for our own player but also for any other player joining from a different device.

When an object gets spawned with Runner.Spawn it gets automatically replicated to all other clients, so it should only be called when PlayerJoined is called for the local player's join.

Add the CarSpawner component to the Prototype Runner GameObject and assign the Car prefab to it.

With this, car spawning is fully setup.

Enter play mode and a car will appear in the scene. The car is able to move, but we will be improving its networked behaviour in the following section.

Next: Essential Forecast Vehicle Physics Tutorial 5 - Car Adjustments

Back to top