- Home /
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
Share the code so we can help you without going and installing unity sample projects.
Answer by flaviusxvii · Oct 15, 2013 at 06:50 PM
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
http://docs.unity3d.com/Documentation/ScriptReference/Vector3-sqrMagnitude.html
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.
Sine you have to check the distance to every object, you might as well do that first, and then make decisions about the objects later..
import System.Collections.Generic;
var sortedByDistance = new SortedDictionary.<float, GameObject>();
for(var seek : GameObject in seeks) {
var distance = (seek.transform.position - position).sqr$$anonymous$$agnitude;
sortedByDistance.Add(distance, seek);
}
var count : int = 0;
for(var distance in sortedByDistance.$$anonymous$$eys) {
count++;
if(count == 1) {
seekOne = sortedByDistance[distance];
continue;
}
if(count == 2) {
seekTwo = sortedByDistance[distance];
continue;
}
break;
}
Your answer
Follow this Question
Related Questions
How could I calculate the distance to recieve the nearest object to the player? 2 Answers
Find nearest object using Physics.OverlapSphere 2 Answers
Get nearest object and find direction problem 2 Answers
Physics.OverlapSphere to get 5 Nearest objects 0 Answers
Manipulating Instanced Object 2 Answers