Hi,
I have a simple code to find the nearest object from a gameObject but I have this error message:
error CS0161: not all code paths return a value.
Here is my simple code:
float ClosestCatcher(out float distanceToClosestCatcher, out Transform nearestCatcher)
{
hitColliders = Physics.OverlapSphere(Chick.position, OverlapRadius, 1 << Catchers);
if (hitColliders.Length != 0)
{
for(int i = 0; i < hitColliders.Length; ++i)
{
distanceToClosestCatcher = Vector3.Distance(Chick.position, hitColliders[i].transform.position);
nearestCatcher = hitColliders[i].transform;
}
else
{
nearestCatcher = null;
distanceToClosestCatcher = Mathf.Infinity;
}
}
}
But as I can see all code paths return a value. So do you have any ideas ? Because I need both values the distance and the Transform.
And if someone would suggest a possible optimization it’s welcome.
You have “float” as return value (written in front of the method name) but you do not use the return keyword anywhere.
So, you probably don’t want to return something (since you are using out parameters), so, just use “void” instead.
However, having multiple out parameters is often a bit clumsy. Instead you could use an own class or struct as return value or a tuple (which are cool with the new C# features).
Also, don’t check always the distance. It requires a square root operation internally which is costly. instead, you can use the squared distance.
Here is an example of how would I write the method (with struct as return value and all required information is passed in to the method, so the method can be declared static):
public struct CollisionInfo
{
public float SquaredDistance;
public Transform ClosestCatcher;
public float Distance { get { return Mathf.Sqrt(SquaredDistance); } }
}
static CollisionInfo GetClosestCatcher(Vector3 position, Collider[] hitColliders)
{
CollisionInfo result = new CollisionInfo();
result.SquaredDistance = float.MaxValue;
foreach(Collider collider in hitColliders)
{
float distanceSqared = Vector3.SqrMagnitude(position - collider.transform.position);
if(distanceSqared < result.SquaredDistance)
{
result.SquaredDistance = distanceSqared;
result.ClosestCatcher = collider.transform;
}
}
return result;
}
2 Likes
Thank you [Hosnkobf]( Problem with a function returning multiple values members/hosnkobf.1165135/), that’s a perfect answer ! I completely missed the float instead of void. And thx for the nice struct you did.