Camera

I have made my camera follow my player speed ans position throughout a level. the problem I am having is that when the player gets destroyed the game camera in the unity editor is still running off of the player.

public class PlayerCam : MonoBehaviour {

    public Transform player;
    public Vector3 offset;

    void Update ()
    {

       transform.position = player.position + offset;
    }
}

Just parent the camera to your player object. Just drag and drop the camera into your player object and position and rotate it accordingly =)

I have as it follows the players movement it keeps coming up with ! MissingReferanceException the object of type ‘Transform’ has been destroyed but your are still trying to access it.

That’s because the player is null (since it has been deleted). Change the update code to this to check if the player is null.

void Update ()
    {
       if(player != null)
       {
              transform.position = player.position + offset;
       }
    }

heres the player movement script.

public class PlayerMovement : MonoBehaviour {

    public Rigidbody rb; //referance to the RigidBody
    public float forwardForce = 2000f; //cube slide speed forward
    public float sidewaysForce = 500f; // cube slide speed sideways

    // Use this for initialization
    void Start ()
    {
      
    }
   
    // Update is called once per frame
    void FixedUpdate ()
    {

        //Input.GetMouseButtonDown((0));

        // Adds a forward force to the rigid body
        rb.AddForce(0, 0, forwardForce * Time.deltaTime);

        if(Input.GetKey("d"))
        {
            rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange); // speed of the cube right
        }

        if (Input.GetKey("a"))
        {
            rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange); // speed of the cube left
        }

        if(rb.position.y < -1f)
        {
            FindObjectOfType<GameManager>().EndGame();
        }
    }
}

i posted in the update function and it still come up with the problem

What problem is still happening the null reference exception? That means that you are trying to use a variable that doesn’t contain anything. Double click it so it takes you to the line with the exception and post it here

public class Score : MonoBehaviour {

    public Transform player;
    public Text scoreText;

    // Use this for initialization
    void Start () {
     


    }
   
    // Update is called once per frame
    void Update ()
    {
        scoreText.text = player.position.z.ToString("0" + "");
    }
}
void Update ()
    {
        if(player != null)
        {
            scoreText.text = player.position.z.ToString("0" + "");
        }
    }

It works. Thank you

1 Like