SmoothFollow not following Instantiated object

Hello, I’ve tried to find a solution to this on here, but nothing fits to make my scene work as intended. SmoothFollow follows my GameObject as long as it’s created before the game is ran, but when I try to attach the prefab, it won’t follow anything. From what I’ve read, it’s because the prefab will be a “clone” so it’s named differently.

Long story short, how do I get the camera to follow my prefab player after it is Instantiated into the scene?

public Transform target;
public float camDist = 10.0f;
public float height = 5.0f;    
public float heightDamping = 2.0f;
public float rotationDamping = 3.0f;

void LateUpdate()
{

    if (!target)
    {
        return;
    }

    float wantedRotationAngle = target.localEulerAngles.y;
    float wantedHeight = target.position.y + height;
    float currentRotationAngle = transform.localEulerAngles.y;
    float currentHeight = transform.position.y;

    currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);

    currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);

    var currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);

    transform.position = target.position;
    transform.position -= currentRotation * Vector3.forward * camDist;

    transform.position = new Vector3(transform.position.x, currentHeight, transform.position.z);

    transform.LookAt(target);

    CompensateForWalls();
}

Thank you in advance!

Hey @TwitchyOrphan

So, the camera needs to identify the target at runtime so we need a way to find it.

This is the way that I have done it and it worked ok for me. Tag the prefab with “Player” which carries through when the object is instantiated. Have the camera script search for an object with that tag and assign it to the target variable.

I used a TimeToSearch variable which allowed me build in a lag for when then player gets destroyed and has a 3 second lead time before being spawned again.

Give this a try:

private float nextTimeToSeach = 0;

private void Update()
{
    if (target == null) 
	{
        if (nextTimeToSeach >= Time.time) 
		{
            GameObject player = GameObject.FindGameObjectWithTag("Player");
            if (player == null) return;
            target = player.GetComponent<Transform>();
        } 
		else 
		{
            nextTimeToSeach++;
        }

    }
    
	if (target == null) return;
}