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*.transform.position.x;*
_ tempz = waypoints*.transform.position.z;_
_ dx = Mathf.Abs (cur.x-tempx);_
_ dz = Mathf.Abs (cur.z-tempz);_
_ dd = Mathf.Sqrt ((dxdx)+(dzdz));_
_ if (dd<cd)_
_ {_
_ cd = dd;_
_ cWay = waypoints;
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().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