It is more than likely an issue with your yield in the coroutine never being hit, thus the coroutine just starting over and over again without ever letting the frame end, or potentially an issue with your loop that is comparing the vectors never exiting. There is absolutely zero chance that comparing 20 Vector3 values even without using the sqrMagnitude optimisation in itself would cause you a stack overflow.
To be sure we would need to see the code you’ve written for the coroutine and calculations, then we can work out from that whats going wrong.
In the meantime I’ve written up this example. It creates a random colleciton of vectors and then starts a coroutine that will just find the nearest one to the transform once a frame. This will continue until StopComparisons is called, and can be restarted with StartComparrisons.
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour
{
[SerializeField]
private float testScale = 10.0f;
[SerializeField]
private Vector3 nearest;
private Vector3[] myVectors;
private Coroutine comparisonRoutine;
public void Awake()
{
myVectors = new Vector3[20];
for (int i = 0; i < myVectors.Length; i++)
{
myVectors _= new Vector3(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f)) * testScale;_
}
StartComparisons();
}
public void StartComparisons()
{
// No sense starting it again if its already running.
if (comparisonRoutine == null)
{
comparisonRoutine = StartCoroutine(_Compare());
}
}
public void EndComparisons()
{
if (comparisonRoutine != null)
{
StopCoroutine(comparisonRoutine);
comparisonRoutine = null;
}
}
private IEnumerator _Compare()
{
while (true)
{
nearest = myVectors[0]; // since we always have a closest, lets start by assuming that it’s the first item.
float nearestDist = Vector3.Distance(nearest, transform.position);
for (int i = 1; i < myVectors.Length; i++)
{
float tempDist = Vector3.Distance(myVectors*, transform.position);*
if (tempDist < nearestDist)
{
nearestDist = tempDist;
nearest = myVectors*;*
}
}
yield return null;
}
}
}
Notice that the while loop ensures the coroutine will continue running unless explicitly stopped (or if you added a break in for some reason, in which case you’d want to null the comparisonRoutine variable at the end of the coroutine).
Since you are calling this constantly you could just write a “FindNearest” method and call it in the update loop, however coroutines are useful as you could easily change it to only update the nearest every X frames or seconds.
Hope this example helps you work out where your initial code when wrong.