Follow Script Not Working

Updated on August 14, 2018 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
5 on August 7, 2018

Hi, I am trying to make a alien follow a player. I have a script but it only follows to the starting point of the player and not follow on wards. This is my script (P.S I referenced everything) – 

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

public class Move : MonoBehaviour {

public UnityEngine.AI.NavMeshAgent agent;
public Transform target;
void Update()
{
agent.SetDestination(target.position);
}
}

  • Liked by
Reply
3 on August 8, 2018

Hi, instead of calling SetDestination only, call SetDestination given a condition. So, in my game, I use the following:

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

public class Temp : MonoBehaviour {

    NavMeshAgent agent;
    public Transform target;
    public int distanceToTarget;

    // Use this for initialization
    void Start () {
        agent = GetComponent<NavMeshAgent>();   
    }
    
    // Update is called once per frame
    void Update () {
        //calcuates absolute distance between the target and the follower.
        distanceToTarget = Mathf.RoundToInt((target.position – transform.position).magnitude);
        //checks if player distance is smaller than stopping distance
        if(distanceToTarget > agent.stoppingDistance)
        {
            //sets destination
            agent.SetDestination(target.position);
        }

    }
}

 

So, using the stopping distance function as a condition to be met, the destination keeps updating so follows the player until it is close enough. Hope this helps, good luck!

P.S. the variable distanceToTarget doesn’t need to be an int, I just wrote that way to tailor my game.

on August 9, 2018

Hi, I tested it and came it came up as a error. This Line a code was ” WRONG ” – 

distanceToTarget = Mathf.RoundToInt((target.position – transform.position).magnitude);

P.S Bold points don’t work. 

on August 9, 2018

Hey i just tested it on an example scene and no errors came up, what did the error message say?

on August 14, 2018

I fixed it the error but it still doesn’t work. ( It Does the same thing as my last script )

Show more replies
  • Liked by
Reply
Cancel
0 on August 9, 2018

Thanks you, I will check if it works and get back to you 🙂

  • Liked by
Reply
Cancel