Is this code expensive?

function Closest(){
var seeks : GameObject;
seeks = GameObject.FindGameObjectsWithTag(“Ally”);
var distance = 100;
var distance2 = 100;
var position = transform.position;
var seekOne : GameObject;
var seekTwo : GameObject;
var seekThree : GameObject;
for(var seek : GameObject in seeks){
var seekDistance = Vector3.Distance(seek.transform.position, position);
if(seekDistance < distance){
if(seekOne){
var seekOneDistance = Vector3.Distance(seekOne.transform.position, position);
if(seekDistance < seekOneDistance){
seekTwo = seek;
}
else if(seekDistance > seekOneDistance){
seekTwo = seekOne;
seekOne = seek;
}
}
else{
seekOne = seek;
}
/seekThree = seekTwo;
seekTwo = seekOne;
seekOne = seek;
/
//distance = seekDistance;

		}
	}
	target = seekOne;
	targetTwo = seekTwo;
	targetThree = seekThree;	
}

Hi! I turned Unity’s example code for finding nearest object into code that finds 2 nearest objects… and it works. My question is, is this code very expensive as it has to be calculated every frame? I don’t quite know yet what makes the code more expensive? Are if statements one of those?

Edit: pic

You didn’t post any code…

But"nearest" naturally involves distance, and finding the distance between two points is generally expensive. Since you don’t need the actual distance, and just the “relative distances” you can save some time using

Unity - Scripting API: Vector3.sqrMagnitude

There are tons of other optimizations you can do. But that’s the best place to start. It will all depend on how many objects you need to check… any more than 20 or 30 and you’d probably benefit from using some kind of space partitioning, or using the collision detection in Unity to quickly grab all of the nearby candidates.