So building a tower defense game and needed to use navMesh for enemy pathing since the enemies need to path around new things, not just along a completely set path. Anyway, since I’ll need to instantiate enemies I can’t use public variables for the waypoints, as such I made a waypoints script to index them. It works fine as far as I can tell and is this:
using UnityEngine;
public class Waypoints : MonoBehaviour
{
public static Transform[] points;
void Awake()
{
points = new Transform[transform.childCount];
for (int i = 0; i < points.Length; i++)
{
points[i] = transform.GetChild(i);
}
}
}
So that’s attached to the parent of the waypoints.
Now I make my Enemy Navigation ai and it’s able to navigate to the first point, then gets stuck there. Right as the enemy is instantiated it has a NullReferenceException:
“NullReferenceException: Object reference not set to an instance of an object
NewNav.Awake () (at Assets/Scripts/NewNav.cs:19)”
The script is telling me it can’t reference the first waypoints script, though it still finds the first point from that same waypoints script, am I incorrect?
Here’s the navigation script that’s giving me the NullReferenceException:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class NewNav : MonoBehaviour
{
private Transform target;
private int wavepointIndex = 0;
private NavMeshAgent agent;
void Awake()
{
agent = GetComponent<NavMeshAgent>();
target = Waypoints.points[0];
// Disabling auto-braking allows for continuous movement
// between points (ie, the agent doesn't slow down as it
// approaches a destination point).
agent.autoBraking = false;
GotoNextPoint();
}
void GotoNextPoint()
{
// Set the agent to go to the currently selected destination.
agent.destination = target.position;
// Choose the next point in the array as the destination,
// cycling to the start if necessary.
wavepointIndex = wavepointIndex++;
target = Waypoints.points[wavepointIndex];
}
void Update()
{
// Choose the next destination point when the agent gets
// close to the current one.
if (!agent.pathPending && agent.remainingDistance < 0.05f)
GotoNextPoint();
}
}
If anyone can enlighten me on what it is I’m missing here I’d greatly appreciate (and likely feel like an idiot - I assume this is a stupid error or an easy fix and I’m just 10 years too rusty to be doing this)
Thank you!