- Home /
Cannot get variable from another class. Error: NullReferenceException
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.
Do you instantiate the GameItemContainer class? You need to instantiate to have access to class atributes.
Answer by Magius96 · Mar 18, 2016 at 04:26 PM
Perhaps you should make your entire GameItemContainer class static as well as all members inside it.
I cant because that way I cant read the X$$anonymous$$L file. Xml data is not getting stored in the variables.
I need to have a container and the items inside that Container because it is the Container who stored the X$$anonymous$$L data
Answer by Soraphis · Mar 18, 2016 at 05:20 PM
Im not sure if this will solve your problem but you should consider a singleton approach, something like this:
public class GameContainer{
private static GameContainer instance;
public static GameContainer Instance{
get{
if(instance == null) instance = new GameContainer();
return instance;
}
}
// constructor should be private
private GameContainer(){
// load from XML
}
public List<Item> Items = new List<Item> ();
}
you would call it like: GameContainer.Instance.Items
, and Instance should never be null, because in this case a new instance is created.
Your answer
Follow this Question
Related Questions
Instances of Classes 1 Answer
How to store data in script and attach it later? 0 Answers
Object Instance Error Message Confusion 1 Answer
Creating new instances of classes 2 Answers