I am making a jet boating game and I have been working on the AI. The way it works is it should steer towards the furthest away waypoint within it's line of sight so as to take the smoothest line. The problem is that when I run the game it says "NullReferenceException: Object reference not set to an instance of an object" for line 20 and I have no idea what the problem is.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AI : MonoBehaviour {
Transform targetRotation;
//variable for target to stear towards.
public Transform target;
Vector3 guyInMyCoords;
bool onWater;
//creates a list of waypoints for the path for the boat to follow.
List path;
void Start () {
path.AddRange(GameObject.FindGameObjectsWithTag ("waypoint"));
}
void Update () {
float Furthest = 0;
foreach (GameObject obj in path) {
Transform direction = null;
direction.LookAt (obj.transform);
RaycastHit hit;
Physics.Raycast (transform.position, direction.forward, out hit, Vector3.Distance (obj.transform.position, transform.position));
Debug.Log (hit.collider.tag);
if (hit.collider.tag != "terrain") {
var distance = Vector3.Distance (obj.transform.position, transform.position);
if (distance > Furthest) {
Furthest = distance;
//sets the target for it to stear towards.
target = obj.transform;
}
}
}
if (onWater)
{
rigidbody.drag = 1.8f;
}
else{
rigidbody.drag = 0.2f;
}
onWater = false;
//this stuff controls how it steers towards the target.
Quaternion sup = transform.rotation;
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Vector3.forward, Vector3.up), Time.deltaTime * 3);
transform.eulerAngles = new Vector3(sup.eulerAngles.x,sup.eulerAngles.y,transform.eulerAngles.z);
guyInMyCoords = target.position;
guyInMyCoords = transform.InverseTransformPoint(target.position);
if (guyInMyCoords.x > 0)
{
rigidbody.AddRelativeTorque (Vector3.up * 15);
rigidbody.AddRelativeTorque (Vector3.forward* -0.5f);
}
else
{
rigidbody.AddRelativeTorque (Vector3.up * -15);
rigidbody.AddRelativeTorque (Vector3.forward* 0.5f);
}
}
void OnCollisionStay(Collision other)
{
if (other.gameObject.tag == "water")
{
rigidbody.AddRelativeForce (Vector3.forward* 140);
onWater = true;
}
}
void OnTriggerStay(Collider other)
{
if(other.tag == "waypoint")
{
path.Remove(other.gameObject);
}
}
}
any help would be great. I am fairly new to unity so any tips or advice would be much appreciated. Thank you.
↧