Hi there,
I’ve written a small algorithm to get the closest object of a certain type.
My current algorithm is as follows:
Vector3 pos = this.transform.position;
float minDistance = 30f;
float closest = Mathf.Infinity;
if (pool.explored.Count == 0)
{
closest = minDistance;
}
else
{
var e = pool.explored.GetEnumerator();
while (e.MoveNext())
{
float d = (e.Current.position - pos).sqrMagnitude;
if (d < closest)
{
closest = d;
}
}
}
Where pool.explored is a HashSet that stores Transforms.
The only issue is, this is an exponential time complexity and makes the game suffer pretty badly.
This code is called every frame, (it sort of needs to be every frame as units have differing speeds, as such, a timer would not work. Unless you can suggest a way this is possible).
Each time that closest is less than minDistance it instantiates a new GameObject which will also be added to pool.explored.
You can probably see how this could get progressively more laggy.
Does anyone have any suggestions as to a potential solution to this?
If any more information is required then do let me know.
Thanks.