Pathfindingscript NullReference error
Hey guys, this script should move an object to one transform after the other and then start at the start waypoint again after going through all Transforms in the array. However everytime the object reaches the last waypoint, a NullReference error occurs because targetWayPoint was not set to an instance of an object. I don't know how to solve this. Could someone help?
Script:
public float speed;
public int currentWayPoint;
public Transform[] Waypoints;
public bool FixedRotation;
public bool Loop = true;
private Quaternion FixedRotate;
Transform targetWayPoint;
void Start ()
{
this.transform.rotation = FixedRotate;
}
void Update ()
{
if (targetWayPoint == null)
targetWayPoint = Waypoints [currentWayPoint];
if (currentWayPoint < this.Waypoints.Length)
{
Walk ();
}
if (FixedRotation)
{
transform.rotation = FixedRotate;
}
}
void Walk ()
{
if (this.transform.position == targetWayPoint.position)
{
if (currentWayPoint == (Waypoints.Length - 1) && Loop)
{
targetWayPoint = Waypoints [0];
}
else if (currentWayPoint == (Waypoints.Length - 1) && !Loop)
{
GetComponent<WaypointPathFinding> ().enabled = false;
}
else
{
currentWayPoint++;
targetWayPoint = Waypoints [currentWayPoint];
}
}
transform.forward = Vector3.RotateTowards (transform.forward, targetWayPoint.position - transform.position, speed * Time.deltaTime, 0.0f);
transform.position = Vector3.MoveTowards (transform.position, targetWayPoint.position, speed * Time.deltaTime);
}
When you do reset your "currentWayPoint" index back to zero? Once reaching the last endpoint if feels like you should set that back to the initial waypoint index of 0, otherwise if the transform.position and targetwaypoint.position is still equal it will hit your last else statement on line 46 and increment the currentWayPoint out of the range of the index for the array. Just a thought.
In Line 33 the Script tests if the Object's Position is the same as the target's Position. Once it reached it the next if Statement is called which first tests whether the loop is Set to true and Checks if the current Waypoint is equal to the Waypoints array length $$anonymous$$us 1. If it's true the Code should Set the targetWaypoint back to the first Index of the Waypoints array. This should be the reset
Your answer
Follow this Question
Related Questions
Android UnityPlayer attribute "currentActivity" returns null 1 Answer
NullExecption in a communication between two scripts 0 Answers
new scripts wont work, old scripts work fine. why? new scripts won't do ANY work. 0 Answers
NullReferenceException in FiniteStateMachine with ThirdPersonCharacter 0 Answers