Adding to array, why doesnt this work?

My traffic system contains many separate “paths”, which contains waypoints.

Now I’m trying to automattically link paths together(in Start()), by finding the closest start waypoints to each end waypoint and then get the parents(the waypoint containers) of those start waypoints and assign them to the path script in the current path. Hope that was a good explanation:)

this is my code so far:

// contains an array with the next paths  
// 

var NewPath: GameObject[];
var thisEndNode: Transform;


function Start () {

// find end node(transform) in this path
thisEndNode= transform.Find(GameObject.FindWithTag("EndNode").gameObject.name); 
// find all start nodes
var allStartNodes: Array = GameObject.FindGameObjectsWithTag("StartNode");

 // find closest start nodes and add their parents to NewPath
    for (var potentialStartNode : GameObject in allStartNodes){ 
    
        var diff: Vector3 = (potentialStartNode.transform.position - thisEndNode.position);
        var curDistance = diff.magnitude;
   
        if (curDistance < 3) {     
           NewPath[ NewPath.length ] = potentialStartNode.transform.parent.gameObject;  
            }   
      }
   

}

It should add the closest paths to NewPath, but it just throws an out of range exception…

If should work similar to this:

function GetWaypoints () {
	// Now, this function basically takes the container object for the waypoints, then finds all of the transforms in it,
	// once it has the transforms, it checks to make sure it's not the container, and adds them to the array of waypoints.
	var potentialWaypoints : Array = waypointContainer.GetComponentsInChildren( Transform );
	waypoints = new Array();
	
	for ( var potentialWaypoint : Transform in potentialWaypoints ) {
		if ( potentialWaypoint != waypointContainer.transform ) {
			waypoints[ waypoints.length ] = potentialWaypoint;
		}
	}
}

It’s because the array you’re creating has a fixed size.

var NewPath: GameObject[];

which apparently isn’t set anywhere. so it’s most probably 0 at this point. which means adding an item at index 1 is out of range.

The reason it’s working in the bottom block, is because you’re using the Array class. which probably has its own way to deal with out of range indexes (like actually expanding automatically the array to add a new value)

So, there’s a few solutions for you :

1 - Detect if you need to expand the array, if so, do it, then add the value.

2 - Use a list. and list.add(); (or any collection class that deals with this issue automatically)

You didnt initialise array nor allocate it size.
If you dont know what size will be, use ArrayList and add element to list, it will dynamicaly increase size