Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by garmekain · Mar 18, 2016 at 01:28 PM · nullreferenceexceptionclassesconstructor

Cant load variable of other script from constructor

The thing is, I have a class GameItemContainer which has a static variable Container which is used to store the values imported from an XML file. I have another class named Item in which if I try to get the value of GameItemContainer.Container.items from the class variable's get command everything works fine, but if I call it from the constructor, it returns null for GameItemContainer.Container.

Here is Item.cs:

 using UnityEngine;
 using System.Collections.Generic;
 using System.Xml;
 using System.Xml.Serialization;
 using System.IO;

 public class Item
 {
 public string Name {get;set;}
 public string Price {get;set;}
 [XmlArray("ItemsNeededNames"), XmlArrayItem("ItemName")]
 public List<string> ItemsNeededNames { get; set; }
 public List<Item> ItemsNeeded {
     get {
         List<Item> allItems = GameItemContainer.Container.items; // All good
         List<Item> _neededItems = new List<Item> ();
         for (int i = 0; i < ItemsNeededNames.Count; i++) {
             for (int j = 0; j < allItems.Count; j++) {
                 if (ItemsNeededNames [i].ToLower () == allItems [j].Name.ToLower ()) {
                     _neededItems.Add (allItems [j]);
                     break;
                 }
             }
         }
         return _neededItems;
     }
 }
 
 //Constructors

 public Item() {}
 public Item(string itemName)
 {
     Debug.Log (GameItemContainer.Container); // it prints null

     var allItems = GameItemContainer.Container.items; // NullReferenceException
     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;
             this.ItemsNeededNames = allItems[i].ItemsNeededNames;
             break;
         }
     }
 }
 }

Notice that inside ItemsNeeded I have:

 List<Item> allItems = GameItemContainer.Container.items;

And if I do

 print(GameItemContainer.Container.items[0].ItemsNeeded[0].Name);

from another script it prints what it needs to print, but calling that same thing from the constructor gives me null.

And here is GameItemContainer.cs:

 using UnityEngine;
 using System.Collections.Generic;
 using System.Xml;
 using System.Xml.Serialization;
 using System.IO;

 [XmlRoot("GameItemCollection")]
 public class GameItemContainer
 {
 [XmlArray("Items"),XmlArrayItem("Item")]
 public List<Item> items = new List<Item> ();


 // The problem comes when initializing items like this
 public static Item lighter = new Item("lighter");


 public static GameItemContainer Container = LoadXML ("gameItems");

 private static GameItemContainer LoadXML(string xmlname) {
     return GameItemContainer.Load (Path.Combine (Application.dataPath, "Scripts/XML/" + xmlname + ".xml"));
 }

 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;
     }
 }
 }



It throws the error NullReferenceException: Object reference not set to an instance of an object at line inside the Item constructor

 var allItems = GameItemContainer.Container.items; // NullReferenceException

I think there aren't any errors and I've been struggling with this the past few hours. Any help would be greatly appreciated.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by garmekain · Mar 18, 2016 at 03:40 PM

I found the error. What I needed to do is change

 public static GameItemContainer Container = LoadXML("gameItems");

To

 public static GameItemContainer Container { get { return LoadXML("gameItems "); } }

But this creates another question. Isnt it going to be much less efficient because it has to load the file each time GameItemContainer.Container is used? Any tips to avoid that?

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

3 People are following this question.

avatar image avatar image avatar image

Related Questions

NullReferenceException : Object reference not set to an instance of an object? 0 Answers

Issue with class constructor. 1 Answer

Passing in objects to class constructor 0 Answers

Hitting Serialization depth, need a better way to access parent class 1 Answer

Help with classes and object constructors 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges