Adding to List of Nested Classes
Hi,
I've got an issue with nested classes that I've been struggling with all day. Below is a simplified example of what I'm trying to accomplish. Basically I want to read a list of all the characters in the game and then each character has a list of equipment objects attached to them. I'm using lists because the number of characters or equip-able items will be constantly changing. Everything shows up as expected in the inspector and the script compiles properly. When I run the app though, I get a null reference exception on the following line:
characterList[a].equipmentList.Add(new Equipment() );
It seems I cannot access "equipmentList" to add a new item. I've been digging through Unity Answers and Google and haven't found anything quite like my issue. Is it possible this is a limitation of Unity? If I can get this working I will actually end up with a 2nd level nested class, but as it is, I can't get the 1st level working so I may have to rethink my entire structure.
Any feedback would be greatly appreciated.
Thanks!
using System.Collections.Generic;
[System.Serializable]
public class Character {
public string characterName;
public List<Equipment> equipmentList;
}
public List<Character> characterList;
[System.Serializable]
public class Equipment {
public string itemName;
public int itemWeight;
}
void Start () {
for (int a = 0; a < 10; a++) {
characterList.Add(new Character() );
for (int b = 0; b < characterList.Count; b++) {
characterList[a].equipmentList.Add(new Equipment() );
}
}
}
}
Answer by jdean300 · Jun 08, 2017 at 06:12 AM
You never initialize the equipmentList
.
for (int b = 0; b < characterList.Count; b++) {
if (characterList[a].equipmentList == null)
characterList[a].equipmentList = new List<Equipment>();
characterList[a].equipmentList.Add(new Equipment() );
}
In some cases, Unity will initialize a serializable list for you if it is null, but you cannot rely on it.
That totally works, thank you!
I never thought to initialize the equipment list since I didn't have to do that for the character list.
I was pulling my hair out over this one. You just made my day!
Your answer
Follow this Question
Related Questions
Using the "Contain" method on a list with various variables. 0 Answers
Class with a List of Classes containing a List of Classes 1 Answer
How do I implement lists for this? Or should I? 0 Answers
Collection was modified; enumeration operation may not compute 0 Answers
NullReferenceException: Object reference not set to an instance of an object 0 Answers