Expand script to stop camera from following player

Hi, I’m having a problem figuring out what to do with my script that has the camera follow the player when the player dies. I’m getting the following error:

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.
UnityEngine.Transform.get_position () (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/UnityEngineTransform.cs:28)
Camera2DFollow.Update () (at Assets/Sample Assets/2D/Scripts/Camera2DFollow.cs:28)

Which takes me to the following code snippet:

void Update () {
		
		// only update lookahead pos if accelerating or changed direction
		float xMoveDelta = (target.position - lastTargetPosition).x;

	    bool updateLookAheadTarget = Mathf.Abs(xMoveDelta) > lookAheadMoveThreshold;

		if (updateLookAheadTarget) {
			lookAheadPos = lookAheadFactor * Vector3.right * Mathf.Sign(xMoveDelta);
		} else {
			lookAheadPos = Vector3.MoveTowards(lookAheadPos, Vector3.zero, Time.deltaTime * lookAheadReturnSpeed);	
		}
		
		Vector3 aheadTargetPos = target.position + lookAheadPos + Vector3.forward * offsetZ;
		Vector3 newPos = Vector3.SmoothDamp(transform.position, aheadTargetPos, ref currentVelocity, damping);

		transform.position = newPos;
		
		lastTargetPosition = target.position;

	}
}

Any suggestions would be greatly appreciated! Thanks!

What are the exact error messages?

–

2 Answers

2

Your target has been destroyed and the script is trying to access it. That’s why it is giving you the missing exception.

Do you destroy the player object (or whatever object the target is) when the player dies?

Thanks for the response dmg0600! What I have is the main camera with the player and camera target as children. When the player is destroyed (which is working OK),the camera target should be destroyed with its parent (correct?). I've been trying, unsuccessfully, to destroy the script to stop the camera from trying to access the target. Could you tell me the best way to do that (or if that is what I should be doing)?

–

Thanks for the excellent advice! That works perfectly. May karma come your way in spades!!!

–

Glad to help! If you can, mark it as answered.

–

Ah, I see I can't yet vote up (need 15 karma), but I can accept answers! Accepted and appreciated :)

–

The level you want to load is not in the build settings.

Go to Use File->Build Settings… and click add current, or make sure all your levels are in loaded in the build settings.

Good luck!

Thanks Graham and SnotE101, but I just checked the build settings and things look good there. I've edited my first post to include the error message I'm getting (and the Game Over screen will now load after the game crashes/pauses when the error for the transform object is thrown).

–