How to make Player in Unity 2D use certain camera

116 views Asked by At

I am making a 2D game in Unity and it is online (using netcode). When the player is spawned in, a camera is also spawned in with it. I am able to make each camera follow each player properly (script is below) but for some reason, whenever another player spawns in, every players screen switches to the new players camera (including the new player).

The script that makes the camera follow the player:

using UnityEngine;

public class CameraController : MonoBehaviour
{
    public Transform target; // The target object to follow (the player)
    public float smoothSpeed = 0f; // The smoothing speed
    public Vector3 offset; // The offset from the target's position

    private void FixedUpdate()
    {
        // Only move the camera if there is a valid target
        if (target != null)
        {
            // Calculate the desired position for the camera based on the target's position and     the offset
            Vector3 desiredPosition = target.position + offset;
            // Smoothly move the camera towards the desired position
            Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition,     smoothSpeed);
            // Set the camera's position to the smoothed position
            transform.position = smoothedPosition;
        }
    }
}

Edit: I found a question online that might help, but i'm not sure how to use it: https://answers.unity.com/questions/1128271/network-multiple-cameras.html

I added this to my code:

void Update()
{
    if (!IsLocalPlayer)
    {
        cam.enabled = false;
        return;
    }
}

But this won't let the camera follow the player

0

There are 0 answers