I can't get the the null check to stop my camera from following the player after they die

Hey all, I have a quick question I can’t seem to find the answer to.
I have my camera following the player object and when they die I get this

“MissingReferenceException: The object of type ‘Transform’ has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
CameraFollow.FixedUpdate () (at Assets/Scripts/CameraFollow.cs:13)”

This is my current script

using UnityEngine;
 
public class CameraFollow : MonoBehaviour
{

    public Transform player;
    public Vector3 offset;

    void FixedUpdate()
    {

        Vector3 setPosition = transform.position;
        setPosition.y = player.transform.position.y + offset.y;
        setPosition.z = player.transform.position.z + offset.z;
        transform.position = setPosition;
    }

}

I have another game object following the player as well and use “if (player != null)” before the main script on that to stop the script if the player is dead however when I add it in fixed update above the Vector3 setPosition I get
“Error CS1023 Embedded statement cannot be a declaration or labeled statement” for line 13 which is the Vector3 line, and 3 more error messeges telling me setPosition does not exist in current context for the following 3 lines. I’m not sure what I’m doing wrong, any help would be appreciated.
Thanks!

First of all, please, put your code in code tags. How to is here .

Second, please post what kind of error messages you get and what is the code you’re trying.

Alternatively you can try to disable the CameraFollow script when your player dies and turn back on when you respawn it.

My bad! I fixed the code tag and posted the error messages.

My guess is you forgot the brackets.

using UnityEngine;
public class CameraFollow : MonoBehaviour
{
    public Transform player;
    public Vector3 offset;
    void FixedUpdate()
    {
        if( player != null ) {
            Vector3 setPosition = transform.position;
            setPosition.y = player.transform.position.y + offset.y;
            setPosition.z = player.transform.position.z + offset.z;
            transform.position = setPosition;
        }
    }
}
2 Likes

Agree.

1 Like

You are quite right! Well, I feel silly. Thank you for your help!