AI Pathfinding problem

ScriptingNub

New member
Joined
Aug 14, 2016
Messages
2
Programming Experience
Beginner
Hello. I'm trying to create a short script that controls a gameObject in Unity to navigate towards targets in a set order. Using the navMesh feature.

So far my script is:

using UnityEngine;
using System.Collections;

public class Nav : MonoBehaviour
{
public Transform destination;
public Transform destination1;
public Transform destination2;
public Transform destination3;
public Transform destination4;

public NavMeshAgent agent;


void Start()
{

agent.SetDestination(destination.position);
}




void Update()
{
if (!agent.pathPending)
{

if (agent.remainingDistance <= agent.stoppingDistance)
{

if (!agent.hasPath || agent.velocity.sqrMagnitude == 0f)
{
agent.SetDestination(destination1.position);

}
}


}


}

}

(Target locations are variables destination1, destination2 etc)

My AI gameObject navigates towards the first target gameObject. If Statements to see if the AI has stopped moving then moves towards the second one. But I'm totally stuck on how to make my AI navigate towards other game objects.

I attempted to just copy and paste the if statement chunk and change the variable accordingly but that worked but also did not work. What I mean is my AI went from the first Target Location gameobject to the second, third. Then back to second and back to third then back to second and so on. i don't know why?
 
This is how I attempted to make my AI gameobject navigate towards all my locations.

using UnityEngine;
using System.Collections;

public class Nav : MonoBehaviour
{
public Transform destination;
public Transform destination1;
public Transform destination2;
public Transform destination3;
public Transform destination4;

public NavMeshAgent agent;






void Start()
{

agent.SetDestination(destination.position);




}


void Update()
{
if (!agent.pathPending)
{

if (agent.remainingDistance <= agent.stoppingDistance)
{

if (!agent.hasPath || agent.velocity.sqrMagnitude == 0f)
{
agent.SetDestination(destination1.position);

}


}




}

//
if (!agent.pathPending)
{

if (agent.remainingDistance <= agent.stoppingDistance)
{

if (!agent.hasPath || agent.velocity.sqrMagnitude == 0f)
{
agent.SetDestination(destination2.position);

}


}




}
//
if (!agent.pathPending)
{

if (agent.remainingDistance <= agent.stoppingDistance)
{

if (!agent.hasPath || agent.velocity.sqrMagnitude == 0f)
{
agent.SetDestination(destination3.position);

}


}




}
//
if (!agent.pathPending)
{

if (agent.remainingDistance <= agent.stoppingDistance)
{

if (!agent.hasPath || agent.velocity.sqrMagnitude == 0f)
{
agent.SetDestination(destination.position);

}


}




}
//

}





}
 

Latest posts

Back
Top Bottom