Camera movement won't follow the player after respawning

Hi! I’m currently making a platforming game, and have now come to the stage of making the player respawn. That does work, however, when the player respawns, the camera won’t follow the player anymore, and I’m not sure where to start to have the camera keep on following the player. Here below is my code for the camera movement, I think I’ve got to fix it in here, if anyone has any tips or knows how to fix this, I’d be very thankful!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraMovement : MonoBehaviour
{

    public Transform controller;


    // Update is called once per frame
    void Update()
    {
        transform.position = controller.transform.position + new Vector3(0, 1, -5);

    }
}

The above code relies on putting the original player into the controller slot.

Thus when the new player spawns, it’s a different player, and this code won’t know about it.

One option is to check if controller is still valid, and if it is not, use some kind of service locator pattern, such as one of the find or get methods, to locate the player at runtime, coupled with disabling the above code from running during the time the player is not present (if there is a delay before respawning, for example).

If you will only ever have one player, you can cheat a bit and use a public static reference to the player inside his script, and have the player set that to himself in his OnEnable() method, then this script will use that static reference to cheat and find the one player in the game. Obviously this only works until you want to do multiplayer. :slight_smile:

1 Like

Ooh, thanks a lot! That kinda makes sense, I’ll see if I can work that out!