- Home /
Question by
uskak41kw · May 02, 2013 at 06:24 PM ·
physics.overlapsphere
Physics.OverlapSphere retunr
Hello! Im getting error: not all code paths return a vale I know, i must return something but i can't solve it. return nearestmob; or return nearestmob.collider; wont help. i need a closest target from this part.
public Collider SortTargets()
{
Collider[] cols = Physics.OverlapSphere(this.transform.position, attackMaximumDistance);
foreach (Collider col in cols)
{
if (col.tag == "Monster")
{ Debug.Log("wee");
if ((Vector3.Distance(col.transform.position, turretHead.position) < closestMobDistance) || closestMobDistance == 0)
{
closestMobDistance = Vector3.Distance(col.transform.position, turretHead.position);
nearestmob = col.gameObject;
return nearestmob.collider;
}
}
}
}
Comment
Best Answer
Answer by whydoidoit · May 02, 2013 at 06:25 PM
You are returning in the wrong place anyway!!
public Collider SortTargets()
{
Collider[] cols = Physics.OverlapSphere(this.transform.position, attackMaximumDistance);
foreach (Collider col in cols)
{
if (col.tag == "Monster")
{ Debug.Log("wee");
if ((Vector3.Distance(col.transform.position, turretHead.position) < closestMobDistance) || closestMobDistance == 0)
{
closestMobDistance = Vector3.Distance(col.transform.position, turretHead.position);
nearestmob = col.gameObject;
}
}
}
return nearestmob.collider;
}
And BTW that is horribly inefficient - try this:
public Collider SortTargets()
{
Collider[] cols = Physics.OverlapSphere(this.transform.position, attack$$anonymous$$aximumDistance);
var turretPosition = turretHead.position;
foreach (Collider col in cols)
{
if (col.tag == "$$anonymous$$onster")
{ Debug.Log("wee");
var dist = ((col.transform.position - turretPosition).sqr$$anonymous$$agnitude;
if ( dist < closest$$anonymous$$obDistance) || closest$$anonymous$$obDistance == 0)
{
closest$$anonymous$$obDistance = dist;
nearestmob = col.gameObject;
}
}
}
return nearestmob.collider;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613101420im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Cannot convert 'UnityEngine.Collider[]' to 'UnityEngine.gameObject[]' using OverlapSphere 3 Answers
How to fix the player flying into the sky after applying velocity on the y to him. 1 Answer
Get distance from all objects in an Collider[] and compare 1 Answer
Question: how to overlap 2 cubes objects 0 Answers
AI Turret Targeting System 2 Answers