# Distance between a waypoint and the object

I have calculate the distance between an object and waypoints. I have taken waypoints as transform, which is an array. The problem is:- I am not able to calculate the distance between the object and respective waypoints in the code.

Despite giving `var k,l,m,.... = Vector3.Distance(waypoint[0,1,2,...].position,object.transform.position);` I am not able to find the distance. If I haven’t given the waypoints in an array, the code will work. But I have to give it in an array. But how!

Say you have N waypoints and should be stored in a array wayPoints.First create wayPoints with N elements and initialise.

var wayPoints: Transform;

var distances: float;

var myObject: GameObject;

var N: int = 5; //initialise yours

function Start()
{

initWayPoints();

}

function initWayPoints()
{

wayPoints = new Transform[N];

distances = new float[N];

//asume your waypoint objects are stored in wayPoints ,such that

//wayPoints = ObjA.transform;

//wayPoints = ObjB.transform;

//wayPoints = ObjC.transform;

//…

//…

//wayPoints[N-1] = ObjN.transform;

}

function calcObjectToWayPoints()
{

``````for( var i  = 0 ; i < N ; i++)
{
if(wayPoints*)*
``````
• {*

distances = (wayPoints*.position - myObject.transform.position).magnitude;*

* }*
* else*
* {*

* print(“way point not set to wayPoints”);*

* }*
}
}
function Update()
{
calcObjectToWayPoints();
for( var i = 0 ; i < N ; i++)
{
print(“distances[” + i + “]:”+ distances );
}
}

The distance between any two points in 3d space is a simple formula:

``````dist = sqrt((x2-x1)^2 + (y2-y1)^2 + (z2-z1)^2)
``````