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
2
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.
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
Last updated