- Home /
Keep getting index out of range exception?
The code below should move my unit from point to point using the aron granberg pathfinding project. Path p: has a Vector3 array "VectorPath" storing theses points and my character should progress through all the points reaching the last one and at said point Path p is set to null. When path is null Fixed Update should not call any movement logic as I've set it to return prior to any calls. Anyway instead of stopping before the logic in the catch I've set use a bool operator and instead continues to make calls on the now null path class and the undeclared Vector3[] VectorPath and get null reference error/ index out of range.`public float speed = 0.2f; public float unitRotForce = 10; bool followingUnit = false; bool patrolSet = false; Vector3 patrolA; Vector3 patrolB; Quaternion _lookRotation; Vector3 _direction; public void MoveTo(Vector3 moveTo) { //Debug.Log (moveTo); seeker.StartPath (transform.position, moveTo, OnPathComplete); currentWaypoint = 0; }
// Fixed Update. Calls that need to be made consistent
void FixedUpdate ()
{
// Unit Attack Updates
if (attackingUnit && Time.time >= attackTime)
{
AttackOut ();
attackTime = Time.time + attackInterval;
}
if (followingUnit)
{
if (Vector3.Distance(transform.position, toAttack.transform.position) > attackRange)
{
if (Vector3.Distance(origActionUnitPos, toAttack.transform.position) <= 0.2f)
{
MoveTo(toAttack.transform.position);
origActionUnitPos = toAttack.transform.position;
}
}
}
// Unit Movement Updates
if (currPath == null) {
//We have no path to move after yet
return;
}
// Unit Rotation Updates
_direction = (currPath.vectorPath[currentWaypoint] - transform.position);
_lookRotation = Quaternion.LookRotation (new Vector3(_direction.x, 0, _direction.z));
transform.rotation = Quaternion.Slerp (transform.rotation, _lookRotation,
Time.deltaTime * unitRotForce);
//Direction to the next waypoint
Vector3 dir = (currPath.vectorPath[currentWaypoint]-transform.position).normalized;
dir *= speed * Time.fixedDeltaTime;
controller.SimpleMove (dir);
//Check if we are close enough to the next waypoint
//If we are, proceed to follow the next waypoint
if (Vector3.Distance (transform.position,currPath.vectorPath[currentWaypoint]) <= 2f) {
if (currentWaypoint > currPath.vectorPath.Count) {
Debug.Log ("End Of Path Reached");
currPath = null;
return;
}
currentWaypoint++;
if (currentWaypoint == currPath.vectorPath.Count && patrolSet)
{
if (currPath.vectorPath[currentWaypoint] == patrolA)
{
MoveTo (patrolB);
}
else
{
MoveTo (patrolA);
}
}
return;
}
}`
Please format your code. If you don't know how, watch the tutorial video on the right and read the FAQ.
Your answer
Follow this Question
Related Questions
Float seen as Object, help? 1 Answer
How to use a JS Array() with #pragma strict? 1 Answer
Is this considered bad coding 1 Answer