Search Unity

[Solved]

Discussion in 'Scripting' started by GhulamJewel, Dec 16, 2014.

  1. GhulamJewel

    GhulamJewel

    Joined:
    May 23, 2014
    Posts:
    351
    [Solved]
     
    Last edited: Feb 16, 2015
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    You probably need to drag the player transform onto the script of the prefab. If you didn't want to do that, you could use GameObject.Find or FindWithTag to initialize the variable in the start function.
     
  3. GhulamJewel

    GhulamJewel

    Joined:
    May 23, 2014
    Posts:
    351
    Thank you for directing me to the right direction. It worked with the FindWithTag.

    Code (CSharp):
    1. using System.Collections;
    2.  
    3. public class FollowScript : MonoBehaviour {
    4.    
    5.     public Transform target;//set target from inspector instead of looking in Update
    6.     public float speed = 3f;
    7.    
    8.    
    9.     void Start () {
    10.        
    11.     }
    12.    
    13.     void Update(){
    14.        
    15.         //rotate to look at the player
    16.         target = GameObject.FindWithTag ("Player").transform;
    17.         transform.LookAt(target.position);
    18.         transform.Rotate(new Vector3(0,-90,0),Space.Self);//correcting the original rotation
    19.        
    20.        
    21.         //move towards the player
    22.         if (Vector3.Distance(transform.position,target.position)>1f){//move if distance from target is greater than 1
    23.             transform.Translate(new Vector3(speed* Time.deltaTime,0,0) );
    24.         }
    25.        
    26.     }
    27.    
    28. }