Hey everyone,
I have a piece of code that can be simplified to this:
private List<List<int>> tempListListInt = new List<List<int>>();
private List<int> tempListInt = new List<int>();
void Start()
{
StartCoroutine(TestListListInt());
}
IEnumerator TestListListInt()
{
int tempInt;
for (int i = 0; i < 10; i++)
{
tempListInt.Clear();
yield return null;
for (int j = 0; j < 10; j++)
{
tempInt = Random.Range(0, 10);
tempListInt.Add(tempInt);
}
tempListListInt.Add(tempListInt);
}
}
when reading tempListListInt each List < int > stored inside is a copy of a List < int >tempListInt generated for i=9. I suppose I screwed something up with accessing global tempListListInt, but I am at loss as to what exactly. Help, pretty please?
Instead of List<List<int>> try using a class, like this
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class IntList
{
public List<int> list = new List<int>();
}
public class : MonoBehaviour
{
private List<IntList> tempListListInt = new List<IntList>();
private IntList tempListInt = new IntList();
void Start()
{
StartCoroutine(TestListListInt());
}
IEnumerator TestListListInt()
{
int tempInt;
int total = 0;
tempListListInt.Clear();
for (int i = 0; i < 10; i++)
{
tempListInt.Clear();
yield return null;
for (int j = 0; j < 10; j++)
{
tempInt = Random.Range(0, 10);
total += tempInt;
tempListInt.list.Add(tempInt);
}
tempListListInt.Add(tempListInt);
}
yield return null;
ShowListTotal(total);
}
// shows the total calculated in coroutine
// and total from list
void ShowListTotal(int total)
{
int tempTotal = 0;
for (i = 0; i < tempListListInt.Count; i++)
{
for (j = 0; j < tempListListInt*.list.Count; j++)*
{ tempTotal += tempListListInt*.list[j];* } } Debug.Log("Coroutine total equals " + total + ", list total equals " + tempTotal); } }