- Home /
I cannot get a SetDestination to function within a set array.
I am New to unity and coding but what i am trying to do is have a script that will keep a list of all the roaming AI controlled boxes in the scene so that the attacking AI can find and chase only the closest one. but i cannot get the .SetDestination to find the variable it needs though the rest of the script where the variable ("go") is called there are no issues. on the line for SetDestination it keeps coming back with NullrefrenceException.
here is the code
public class Red_Attack : MonoBehaviour
{
NavMeshAgent nav;
private Creature_Navigation Mynav;
private void Start()
{
Mynav = GetComponent<Creature_Navigation>();
}
void Update()
{
FindClosestEnemy();
}
public void FindClosestEnemy()
{
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("Blue");
GameObject closest;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in gos)
{
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance)
{
closest = go;
distance = curDistance;
Debug.DrawLine(this.transform.position, go.transform.position);
}
if(Vector3.Distance(this.transform.position, go.transform.position) < 20f)
{
Mynav.enabled = !Mynav.enabled;
Debug.Log("AHHHHHH!!");
Debug.DrawLine(this.transform.position, go.transform.position, Color.yellow);
Vector3 targetVector = go.transform.position;
nav.SetDestination(targetVector);
Mynav.enabled = Mynav.enabled;
}
}
}
}
you have a Creature_Navigation script, and, you don't show it, so, we dont know all to help precisely.
I guess, just guess, that you have a nav mesh agent attached to the same GameObject of the script that give te error, so, try on start
private void Start()
{
$$anonymous$$ynav = GetComponent<Creature_Navigation>();
nav = GetComponent<Nav$$anonymous$$eshAgent>();
}
Your a Life saver thank you, that is what it was. i`m still new so simple things i overlook still.
Answer by carl010010 · Feb 07, 2019 at 03:54 AM
Where are you setting your NavMeshAgent "nav"? It looks like it would be null when you try to set the destination.
the problem was already solved, check the comments
@Nebakenezzer please close the question to stop new answers
Your answer
![](https://koobas.hobune.stream/wayback/20220612191242im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
NavMeshAgent resume original position and facing direction C# 0 Answers
My ai is getting stuck when there is a lot of them 0 Answers
NavMesh link does not connect properly on runtime 1 Answer
Need help detecting barriers for my game 0 Answers
How to get a velocity unit vector from a NavMeshAgent? 1 Answer