Can't load array from another class
I want to have a variable containing all game items inside the Item class, but when I try to get the value of GameItemContainer.Container.items it gives me an error.
Item.cs:
public string Name;
public float Price;
// Contructors
public Item() {}
public Item(string itemName)
{
List<Item> allItems = GameItemContainer.Container.items;
for (int i = 0; i < allItems.Count; i++) {
if (allItems[i].Name.ToLower() == itemName.ToLower()) {
this.Name = allItems[i].Name;
this.Price = allItems[i].Price;
break;
}
}
}
GameItemContainer.cs:
[XmlArray("Items"),XmlArrayItem("Item")]
public List<Item> items = new List<Item> ();
public static GameItemContainer Container = LoadXML("gameItems");
private static GameItemContainer LoadXML(string xmlname) {
return GameItemContainer.Load (Path.Combine (Application.dataPath, "Scripts/XML/" + xmlname + ".xml")) as GameItemContainer;
}
public static GameItemContainer Load(string path)
{
XmlSerializer serializer = new XmlSerializer(typeof(GameItemContainer));
using(var stream = new FileStream(path, FileMode.Open))
{
return serializer.Deserialize(stream) as GameItemContainer;
}
}
Error appears in line
List<Item> allItems = GameItemContainer.Container.items;
And it throws the error
NullReferenceException: Object reference not set to an instance of an object
Any help would be greatly appreciated.
Have you verified that
LoadXml("gameItems");
does not return null? I would do that first before continuing any farther. If it does return null, than you know something is wrong with your load.
Also, no need for the "as GameItemContainer" at
return GameItemContainer.Load (Path.Combine (Application.dataPath, "Scripts/X$$anonymous$$L/" + xmlname + ".xml")) as GameItemContainer;
because your GameItemContainer.Load method has a return type of GameItemContainer.
@Brocccoli Yes, it returns something. in another part of code I have:
void Start() {
print (GameStateContainer.Container.items);
}
and it returns System.Collections.Generic.List`1[Item]
That doesn't guarantee that your LoadX$$anonymous$$L method returns anything. All that is printing out is the type of the variable, which it knows because you instantiate it as an empty list.
You need to explicitly check that your LoadX$$anonymous$$L method is returning something you want and not null.
Your answer
Follow this Question
Related Questions
Is it possible to customize how a variable of a certain type would look in the inspector? 1 Answer
Cant load variable of other script from constructor 1 Answer
Access child class variable inside child class script as a parent class of the parent script 0 Answers
Calling Function from another script not working 1 Answer
Scripts unintentionally sharing data (using public classes) 0 Answers