Instantiating a Local Camera

Using a Camera Prefab to instantiate your local player's camera.

With this method of camera management we will instantiate a camera from a prefab we create and assign it to our local player object when it spawns in.

1

Creating a Camera Prefab

Let's start by dragging the Main Camera in the scene into our Project Window to create a prefab out of it. You can now delete the Main Camera from the Scene Hierarchy.

2

Giving the Player a Camera Holder

Now create an empty Game Object on your Player Prefab and position it where you'd like. This will be where we instantiate and position the Camera object.

Camera Holder created on the Player Prefab
3

Writing a PlayerCamera Script

Let's now add the following script to the Player Prefab that we will use to instantiate our Camera Prefab once our player spawns in.

PlayerCamera.cs
using FishNet.Object;
using UnityEngine;

// This script will be a NetworkBehaviour so that we can use the 
// OnStartClient override.
public class PlayerCamera : NetworkBehaviour
{
    [SerializeField] private Camera cameraPrefab;
    [SerializeField] private Transform cameraHolder;

    // This method will run on the client once this object is spawned.
    public override void OnStartClient()
    {
        // Since this will run on all clients that this object spawns for
        // we need to only instantiate the camera for the object we own.
        if (IsOwner)
            Instantiate(cameraPrefab, cameraHolder.position, cameraHolder.rotation, cameraHolder);
    }
}

This script uses the OnStartClient override method from NetworkBehaviour to instantiate the camera prefab for our local player.

4

Assign your References to the Script

Now select the Player Camera component in your Player Prefab and add the Camera Prefab we made to the Camera Prefab field. Also select the CameraHolder game object in the Camera Holder field.

The Player prefab with the Main Camera filled in
5

Test the Camera In-Game

With all that set you should be able to run the game and see how the camera is created for only your local player.

Demonstration of the local camera

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

Source Files Repository

Last updated