Using the Scene Camera

Using the camera in the scene for your local player.

With this method our local player will take control of the Main Camera it finds in the scene.

1

The Main Camera Tag

Before we start we need to ensure our camera object in the scene is tagged as the "Main Camera"

Main Camera in scene with the tag
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 parent 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 take control of our Camera once our player spawns in.

PlayerCamera.cs
using FishNet.Connection;
using FishNet.Object;
using UnityEngine;

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

    // This method is called on the client after gaining or losing ownership of the object.
    // We could have used OnStartClient instead, as we did in the previous example, but using OnOwnershipClient
    // means this will work for a player object we don't initially own but are given ownership to later.
    public override void OnOwnershipClient(NetworkConnection prevOwner)
    {
        if (Camera.main == null)
            return;

        // If we are the new owner of this object, then take control of the camera by parenting it
        // and moving it to our camera holder.
        if (IsOwner)
        {
            Camera.main.transform.SetPositionAndRotation(cameraHolder.position, cameraHolder.rotation);
            Camera.main.transform.SetParent(cameraHolder);
        }
    }
}

This script uses the OnOwnershipClient override method from NetworkBehaviour to instantiate the camera prefab for our local player as soon as he gets ownership of the object. We could just have easily used the OnStartClient override method like the Instantiating a Local Camera example shows.

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 Camera Holder 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 from the scene is controlled by 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