Class with a List of Classes containing a List of Classes
Hello!
I have three Classes, World, Area and Level. World contains a List of Areas, and each Area contains a List of Levels. I was about to set first area's second level's state like areaList[0].levelList[1].state = LevelState.unlocked
, but it seems like it sets all the areas' second levels' state. The fact that i can't set any of the state Enums in the inspector (i can click on them, but nothing happens if i selest a divverent state) is just a bonus. :) What am i doing wrong? Thanks in advance!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum LevelState { locked, unlocked, completed }
public class World : MonoBehaviour {
public List <Area> areaList = new List<Area> ();
void Start () {
List <Level> levelList = new List<Level> ();
for (int i = 0; i < 5; i++) {
levelList.Add(new Level (LevelState.locked, 0));
}
for (int i = 0; i < 5; i++) {
areaList.Add(new Area (false, levelList));
}
areaList[0].levelList[1].state = LevelState.unlocked;
}
}
[System.Serializable]
public class Area {
public bool unlocked;
public List <Level> levelList;
public Area (bool _unlocked, List <Level> _levelList)
{
unlocked = _unlocked;
levelList = _levelList;
}
}
[System.Serializable]
public class Level {
public LevelState state;
public int score;
public Level(LevelState _state, int _score){
state = _state;
score = _score;
}
}
Answer by Hellium · Apr 12, 2018 at 08:57 AM
it seems like it sets all the areas' second levels' state
Of course, because all the areas share the same levelList....
areaList.Add(new Area (false, levelList)); // Here, you provide the same list for every area....
You have to create a new list for every area:
void Start ()
{
for (int areaIndex = 0; areaIndex < 5; areaIndex++)
{
List <Level> levelList = new List<Level> (5);
for (int levelIndex = 0; levelIndex < 5; levelIndex++)
{
levelList.Add(new Level (LevelState.locked, 0));
}
areaList.Add(new Area (false, levelList));
}
areaList[0].levelList[1].state = LevelState.unlocked;
}
facepalm Pfff... Ofcourse. I need a big sleep now... :) Thank you!
Your answer
Follow this Question
Related Questions
How do I modify variables from a different class that belongs to the same C# file? 1 Answer
How to add Script1.List.Class to Script2.List.Class? 0 Answers
Adding to List of Nested Classes 1 Answer
How to create a class and save a list of that object? 0 Answers
NullReferenceException: Object reference not set to an instance of an object 0 Answers