- Home /
Argument out of range exception
Task i am trying to accomplish.
(1) Find all the GameObjects in the scene with the tag "Enemy", and turn that into a list.(gos list)
(2) if the other list (trs list) count is less than the gos list, instance a new gameobject and add its transform to the trs list
can anyone see why I am getting an "Argument out of range" exception at line 42 here after one value is added to the trs list ?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
[System.Serializable]
public class GOb
{
public List<GameObject> gos = new List<GameObject>();
public List<Transform> trs = new List<Transform>();
}
public class listingTest : MonoBehaviour
{
public List<GOb> GOBS = new List<GOb>();
// Update is called once per frame
void Update()
{
CheckAndSet();
}
void CheckAndSet()
{
foreach (var item in GOBS.Select((x, i) => new { Value = x, Index = i }))
{
item.Value.gos = (GameObject.FindGameObjectsWithTag("Enemy")).ToList();
if (item.Value.trs.Count < item.Value.gos.Count)
{
GameObject enemyRep = new GameObject("Enemy");
item.Value.trs.Add(enemyRep.transform);
Debug.Log("added");
}
for (int i = 0; i < item.Value.gos.Count; i++)
{
Debug.Log(item.Value.trs[i]);
}
}
}
}
Answer by UnityCoach · Jan 03, 2017 at 02:06 PM
It's always risky to manage two lists together, I would advise to use a Dictionary. Anyway, the problem here is that you should do a loop and not an if statement, like : So that it adds as many instances.
{
item.Value.gos = (GameObject.FindGameObjectsWithTag("Enemy")).ToList();
for (int a = item.Value.trs.Count, a < item.Value.gos.Count, a++)
{
GameObject enemyRep = new GameObject("Enemy");
item.Value.trs.Add(enemyRep.transform);
Debug.Log("added");
}
for (int i = 0; i < item.Value.gos.Count; i++)
{
Debug.Log(item.Value.trs[i]);
}
}
I see, thanks for re$$anonymous$$d me about Dictionaries. This works but I will try Dictionaries too :)
Answer by dpoly · Jan 03, 2017 at 11:12 PM
You are iterating over the trs list using the gos count. Try
for (int i = 0; i < item.Value.trs.Count; i++)
Your answer
