Search Unity

Smooth Camera Follow(Needs just a few optimizations)

Discussion in 'Scripting' started by bekiryanik, Jun 29, 2015.

  1. bekiryanik

    bekiryanik

    Joined:
    Jul 6, 2014
    Posts:
    191
    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.

    Code (csharp):
    1.  
    2. using Unity Engine;
    3. using System.Collections;
    4.  
    5. public class smoothCamFollow : MonoBehaviour {
    6. public Transform target;
    7. public float smoothTime = 0.3F;
    8. private Vector3 velocity = Vector3.zero;
    9.  
    10. void Update() {
    11.      Vector3 targetPosition = target.TransformPoint(new Vector3(0, 3.85f, -3.03f));
    12.      transform.position = Vector3.SmoothDamp(transform.position, targetPosition, refvelocity, smoothTime);
    13.    }
    14. }
    15.  
    Thank you!
     
    Last edited: Jun 29, 2015
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
  3. bekiryanik

    bekiryanik

    Joined:
    Jul 6, 2014
    Posts:
    191
    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.
     
  4. SomeGuy22

    SomeGuy22

    Joined:
    Jun 3, 2011
    Posts:
    722
    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.

    Code (CSharp):
    1. void Awake ()
    2. {
    3. target = gameObject.FindWithTag("YourTag").transform;
    4. }
    Simple as that. We write .transform after because FindWithTag() returns a type GameObject.
     
  5. bekiryanik

    bekiryanik

    Joined:
    Jul 6, 2014
    Posts:
    191
    That was exatly what i was looking for! Thank you so much!