- Home /
Question by
ragnaros100 · Jan 21, 2013 at 07:03 PM ·
arraylistindexout of range
How do I check a List[0], when it's nothing?
I have made this function (inspired by the bugzerg arcade hack'n'slash tutorial)
public static GameObject ClosestGameObject (string searchTag, Transform ClosestTo)
{
List<Transform> outPutList = new List<Transform>();
outPutList.Clear();
GameObject[] go = GameObject.FindGameObjectsWithTag(searchTag);
foreach(GameObject goes in go)
{
outPutList.Add(goes.transform);
}
outPutList.Sort(delegate(Transform t1, Transform t2) {
return Vector3.Distance(t1.position, ClosestTo.position).CompareTo(Vector3.Distance(t2.position, ClosestTo.position));
});
GameObject output = outPutList[0].gameObject;
return output;
}
But if I feed it a searchTag that isnt on any of the gameObjects in the scene, it gives me an error at line 13: Argument is out of range. Is there any way to check if the go variable contain anything? I know I can't just simply write
GameObjecy[] go = GameObject.FindGameobjectsWithTag("Bleh");
if(go != null)
{
// do stuff
}
else
{
return null;
}
-thanks in advance :)
Comment
Best Answer
Answer by DayyanSisson · Jan 21, 2013 at 07:20 PM
if(go.Length > 0){
// do stuff
}else{
return null;
}
Just check to see how many items are in the array. If it returns 0, then there aren't any.