Smooth Camera Follow(Needs just a few optimizations)

Hello,

I am using below script for smooth camera follow. It does work great but it needs few optimizations. My target is created on screen from a prefab. And it is a problem for me to attach my target to this script as referance after the game is started. How can i attach my target to this script as referance after the game is started? Or, how can i optimize the script according to my target? It should automatically find my target after the game is started.

using Unity Engine;
using System.Collections;

public class smoothCamFollow : MonoBehaviour {
public Transform target;
public float smoothTime = 0.3F;
private Vector3 velocity = Vector3.zero;

void Update() {
     Vector3 targetPosition = target.TransformPoint(new Vector3(0, 3.85f, -3.03f));
     transform.position = Vector3.SmoothDamp(transform.position, targetPosition, refvelocity, smoothTime);
   }
}

Thank you!

Check out GameObject.Find() and / or GameObject.FindWithTag().

I have already tried these. These are also seemed to me the only way to do what i want to do but, i couldn’t find how to use them with the codes i give above.

When you create your target object, make sure it has the appropriate tag, then in your follow script, add the search in the Awake () function, which is called when the script is activated. Or OnEnable() if you have multiple activations.

void Awake ()
{
target = gameObject.FindWithTag("YourTag").transform;
}

Simple as that. We write .transform after because FindWithTag() returns a type GameObject.

That was exatly what i was looking for! Thank you so much!