Smooth Camera follow script is causing framerate drops when moving

Hello there.

I have a big problem with my smooth camera script.
The problem is that whenever i move and the camera follows the player, the framerate drops from 60+ frames per second to only 10+ frames per second and when the player stops moving it goes back to 60+ frames per second almost instantly.

I looked into the Profiler, i looked at posts in the Unity Forums and the Unity Answers, i got Occlusion Culling properly done, i changed the update type and the code dozens of times, but nothing seems to work.

Here is my code :

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

public class SmoothCam : MonoBehaviour {

	// Get the player's transform
	public Transform player;

	// The smoothness value
	public float smoothness;

	// The camera's offset from the player
	public Vector3 cameraPositionOffset;

	void LateUpdate()
	{
		// Update the position of the player and add cameraPositionOffset to it.
        Vector3 updatedPosition = player.position + cameraPositionOffset;
		
		// Lerp the position of the camera
        transform.position = Vector3.Lerp(transform.position, updatedPosition, smoothness);
	} 
	
}

If you know how to fix this issue, please tell me. I really appreciate every answer.

@Cubemation, You are using transform.position which has a performance impact. Each call “transform.position” is using GetComponent of the object.

You need to cache the Transform component and use it instead of transform.position.

Add the following lines into the script:

Transform thisTransform;

void Awake()
{
     thisTransform = GetComponent<Transform>()
}

And then replace the “transform.position” by thisTransform.position. In your case the LateUpdate function should look like:

void LateUpdate()
{
     // Update the position of the player and add cameraPositionOffset to it.
     Vector3 updatedPosition = player.position + cameraPositionOffset;
         
     // Lerp the position of the camera
     thisTransform.position = Vector3.Lerp(thisTransform.position, updatedPosition, smoothness);
} 

In this case the GetComponent will be called only one time at the Awake and then in the LateUpdate function the cached variable will be used without any performance impact.