- Home /
if close to one of a kind?
Well I understand what I need to know as in the methods of Vector3.Distance(a,b);
and also var x: Transform[] or in C# public Transform[] name;
but my question is how would I make it so if I am within distance of any of the array objects what I would imagine looks like: if(Vector3.Distance(object[1 - object.length],transform.position) < distance);
but how would I say one of the objects in the array ?
Answer by aldonaletto · Nov 24, 2011 at 11:33 PM
Your question is very confusing, but I suppose you want to check the distance from one specific element of the array, or from any elements. If you want to verify the distance from the element n of the array, you should use:
if (Vector3.Distance(object[n].position, transform.position) < distance){
// do something
}
But if you want to check all elements in the array, you should use:
for (var i = 0; i < object.length; i++){
if (Vector3.Distance(object[i].position, transform.position) < distance){
// do something
}
}
If you want to know if you're closer than distance to any object in the array, you can use a boolean flag:
var near = false;
for (var i = 0; i < object.length; i++){
if (Vector3.Distance(object[i].position, transform.position) < distance){
near = true;
}
}
if (near){
// do something
}
Answer by kilguril · Nov 25, 2011 at 01:16 AM
To access a member of an array, simply use an index value for the item you wish to access - i.e. object[0], object[1], object[object.Length]
. Also, keep in mind array indices start from 0 and not 1. So if you had an array of 3 items, the index range would be from 0 to 2.
As for testing against all items in an array, use a simple for loop to iterate over all items - see wikipedia for reference
C#
Transform[] arrayOfTransforms;
for (int i=0; i < arrayOfTransforms.Length; i++)
{
arrayOfTransforms[i] // This will access the array at position "i" which iterates over the entire array
}