Question by
trshdnscttrd · Jan 01, 2018 at 08:15 AM ·
navmeshagent
Nav agent destination stuck at instantiation location
Trying to learn the ins and outs of using the Navmesh, and for the life of me cannot get the agent to update the Destination. It is always stuck as the location it was instantiated at. I have tried using both agent.destination = "" and agent.setdestination, both return the same result. Hoping someone could have a look at the code and identify where ive gone wrong. Code is attached to an instantiated enemy unit.
public class EnemyAI : MonoBehaviour { Animator anim; Rigidbody rbody; NavMeshAgent navAgent;
[HideInInspector]
public bool canAttack;
[HideInInspector]
public bool canMove;
private bool attackingPlayer;
[Header("Movement Properties")]
public int movementSpeed;
public int rotationSpeed;
//[HideInInspector]
public List<GameObject> NavPointList; //List array for all local Navpoints
private GameObject player; //Reference to Players position
private Transform myTransform; //Cacheing this objects transform
[SerializeField]
private Transform destination; //destination for NavMesh Agent
private int RandomNavPoint;
void Start()
{
anim = GetComponent<Animator>();
player = GameObject.FindGameObjectWithTag("Player");
AddNavMesh();
canAttack = true;
canMove = true;
attackingPlayer = false;
GetNavPoints();
NextNavPoint();
navAgent.SetDestination(destination.position);
Debug.Log("Actual Destination Position is: " + navAgent.destination);
}
void AddNavMesh()
{
Vector3 sourcePostion = transform.position; //The position you want to place your agent
NavMeshHit closestHit;
if (NavMesh.SamplePosition(sourcePostion, out closestHit, 500, 1))
{
this.transform.position = closestHit.position;
gameObject.AddComponent<NavMeshAgent>();
navAgent = GetComponent<NavMeshAgent>();
navAgent.autoBraking = false;
}
else
{
Debug.Log("Could not add Nav Mesh Agent to " + gameObject);
}
}
void Update()
{
if (canMove)
{
if (attackingPlayer == true)
{
FollowEnemy();
}
if (attackingPlayer == false)
{
Roaming();
}
}
}
//All functions for NPC Roaming
public void GetNavPoints()
{
GameObject[] npt = GameObject.FindGameObjectsWithTag("NavPoint");
foreach (GameObject navPoint in npt)
{
if (navPoint.transform.parent == transform.parent)
{
NavPointList.Add(navPoint);
}
}
}
void Roaming()
{
if (Vector3.Distance(transform.position, destination.position) <= 0.5)
{
NextNavPoint();
navAgent.SetDestination(destination.position);
}
}
void NextNavPoint()
{
RandomNavPoint = Random.Range(0, NavPointList.Count - 1);
destination = NavPointList[RandomNavPoint].transform;
Debug.Log("calculated destination position is: " + destination.position);
}
//All Functions for Combat / Attacking the player
void FollowEnemy()
{
}
}
Comment
Your answer