- Home /
Null reference exception on GameObject
Hi,
I'm making an AI movement script, which just takes the enemy from one waypoint to another. And it works fine, the enemy moves from one waypoint to another, randomly picks another waypoint and begins to travel to it. However i'm constantly getting thrown Null Reference Exceptions
The code is below
using UnityEngine;
using System.Collections;
public class AImovement : MonoBehaviour {
public GameObject[] waypoints;
private bool move = true;
private GameObject cWay;
private Vector3 pos, wTarget;
public float speed = 0.5f;
public float captureRadius = 1;
void Start () {
//Find which waypoint is closest to player
float dd, tempx, tempz,dx,dz, cd=1000;
Vector3 cur = transform.position;
for (int i=0; i<waypoints.Length; i++)
{
tempx = waypoints[i].transform.position.x;
tempz = waypoints[i].transform.position.z;
dx = Mathf.Abs (cur.x-tempx);
dz = Mathf.Abs (cur.z-tempz);
dd = Mathf.Sqrt ((dx*dx)+(dz*dz));
if (dd<cd)
{
cd = dd;
cWay = waypoints[i];
Debug.Log (wTarget + " " + i);
}
}
}
void Update () {
//Do we want to move?
if (move)
{
wTarget = cWay.transform.position;
pos = transform.position;
wTarget.y = pos.y;
transform.LookAt (wTarget);
transform.Translate (new Vector3(0,0,speed), Space.Self);
//Have we reached the target?
if (Vector3.Distance (wTarget,pos) < captureRadius)
{
//Find available waypoints from current waypoint
GameObject[] tempWay = cWay.GetComponent<waypoint>().attached;
int j = 0;
foreach (var s in tempWay)
{
j++;
}
Debug.Log ("Reached");
cWay = tempWay[Random.Range(0, j)];
}
}
}
//External way of modifying the movement
public void movement(bool m)
{
move = m;
}
}
so cWay is the waypoint I want to travel to, and the exception is gettings thrown on line 39 which is
wTarget = cWay.transform.position;
but I set cWay in my start method, and cWay must be set anyway as the enemy travels to the next waypoint. All the waypoints are empty gameobjects which are added to waypoints[]. And each waypoint has a script with a GameObjects array called attached, which holds the way points that can be to travelled to next.
I've really got no idea and any help would be much appreciated, thanks,
Brett
Answer by AchillesWF · May 23, 2012 at 05:12 PM
If nothing stops .attached from potentially holding a null value in the array, then you will get cWay being null. Perhaps when setting up the attached list for one of your waypoints you didn't drag a waypoint into one of the slots? You really should be protecting against this anyway in the line "if (move)" by using something like "if ( (move) && (cWay != null) )".
Also, note that if dd is not < cd, cWay will not have a value on Start.