For Loop: Different count of objects are added to lists
Hello,
I'm trying to add the same amount of objects to two different Lists (bool and string).
The two Lists should have the same amount of index (8 in this case)
for (int i = 0; i < 8; i++)
{
index = 0;
index = Random.Range(0, childs.Count);
SaveGame.currquestobjects.Add(true);
SaveGame.questobjnames.Add(childs[index].name);
Debug.Log(SaveGame.questobjnames.Count);
transform.GetChild(index).gameObject.SetActive(false);
childs.RemoveAt(index);
}
After this, the object should be deactivated and removed from the "childs" list.
My problem: The bools list (currquestobjects) has a Count of 7 while the "questobjnames" has one of 8
Will be thankful for your help!!!!
Sincerely, MG
Great, so if you continue try 1,2,3,...,8 then at what numbers it fails?
Are you sure that there are at least 8 elements in the childs[] array?
I attached this to a GameObject with 8+ empty children and never had a problem, is anything else manipulating your lists? Where is this being called?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ListCountWrong : $$anonymous$$onoBehaviour
{
private List<bool> questObjects;
private List<string> questObjectNames;
private List<Transform> childs;
// Use this for initialization
void Start ()
{
this.childs = new List<Transform> ();
this.questObjects = new List<bool> ();
this.questObjectNames = new List<string> ();
for (int k = 0; k < this.transform.childCount; k++) {
this.childs.Add (this.transform.GetChild (k));
}
for (int i = 0; i < 8; i++) {
int index = 0;
index = Random.Range (0, childs.Count);
this.questObjects.Add (true);
this.questObjectNames.Add (childs [index].name);
Debug.LogFormat ("questObjects: {0}, questObjectNames: {1}", this.questObjects.Count, this.questObjectNames.Count);
childs [index].gameObject.SetActive (false);
childs.RemoveAt (index);
}
}
}
I've just tested and changed several things in several methods and I don't know how and why, but now it works!!!!
Thank you very much for your effort testing this and for your answer!!