• 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 /
avatar image
0
Question by asmit10 · Apr 05, 2017 at 12:42 PM · nullreferenceexception

NullReferenceException when adding an item to a list

I've attempted the other fixes I've seen on Unity answers and Stack Exchange, and I've added breakpoints everywhere within my code and still can't find the thing actually causing the problem. The error is on the first line attempting to add to the Items list.

This made me think that I had to instantiate the list, which is what I attempted to do in my solution, which also threw an exception.

What I started having the problem with:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class ItemList : MonoBehaviour {
 
     public static Sprite[] sprites;
 
     // Use this for initialization
     void Start () {
         //load item sprites
         sprites = Resources.LoadAll<Sprite>("female_robe");
     }
     
     // Update is called once per frame
     void Update () {
         //Debug.Log(sprites.Length);
     }
     
 
     public class Item
     {
         public string Name { get; set; }
 
         public int Rarity { get; set; }
 
         public int Id { get; set; }
 
         public Sprite sprite { get; set; }
         
         public string Type { get; set; }
     }
 
     public static List<Item> Items = new List<Item>();
 
     public static void generateItemsChest()
     {
 
         Items.Add(new Item() { Name = "Note", Id = 1, sprite = sprites[0], Type = "Quest" });
         Items.Add(new Item() { Name = "Sword", Id = 2, sprite = sprites[1], Type = "Weapon" });
         Items.Add(new Item() { Name = "Shield", Id = 3, sprite = sprites[2], Type = "Armor" });
         Items.Add(new Item() { Name = "Spear", Id = 4, sprite = sprites[3], Type = "Weapon" });
         Items.Add(new Item() { Name = "PoleArm", Id = 5, sprite = sprites[4], Type = "Weapon" });
 
     }
 }
 

After looking around I learned that I needed to instantiate the list(?) so I tried this:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class ItemList : MonoBehaviour {
 
     public static Sprite[] sprites;
     //public static List<Item> Items = new List<Item>();
 
     // Use this for initialization
     void Start () {
         //load item sprites
         sprites = Resources.LoadAll<Sprite>("female_robe");
     }
     
     // Update is called once per frame
     void Update () {
         //Debug.Log(sprites.Length);
     }
     
 
     public class Item
     {
         public static List<Item> Items;
 
         public string Name { get; set; }
 
         public int Rarity { get; set; }
 
         public int Id { get; set; }
 
         public Sprite sprite { get; set; }
         
         public string Type { get; set; }
 
         public Item()
         {
             Items = new List<Item>();
         }
     }
 
 
     public static void generateItemsChest()
     {
         Debug.Log(Item.Items.Count);
         Item.Items.Add(new Item() { Name = "Note", Id = 1, sprite = sprites[0], Type = "Quest" });
         Item.Items.Add(new Item() { Name = "Sword", Id = 2, sprite = sprites[1], Type = "Weapon" });
         Item.Items.Add(new Item() { Name = "Shield", Id = 3, sprite = sprites[2], Type = "Armor" });
         Item.Items.Add(new Item() { Name = "Spear", Id = 4, sprite = sprites[3], Type = "Weapon" });
         Item.Items.Add(new Item() { Name = "PoleArm", Id = 5, sprite = sprites[4], Type = "Weapon" });
 
     }
 }
 

Comment
Add comment · Show 1
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
avatar image NoseKills · Apr 06, 2017 at 03:27 PM 0
Share

There's probably nothing wrong with the first example. You just probably call generateItemsChest() before Start() is called so you get a null ref from trying to access sprites[0] before creating the sprite array.

@sohail_786's answer probably works... the only thing it really changes is that sprites is created in Awake and Items in Start(). $$anonymous$$aking the method not static prevents you from calling the method before Awake() as well

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by SohailBukhari · Apr 05, 2017 at 01:22 PM

@username The problem is with your public static List Items;. Your list was not initializing so i change little bit of you script and now working fine.

 using System;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class ItemList : MonoBehaviour
 {
     public List<Item> items;
     public Sprite[] sprites;
 
     private void Awake()
     {
         items = new List<Item>();
         sprites = Resources.LoadAll<Sprite>("female_robe");
     }
 
     private void Start()
     {
         GenerateItemsChest();
     }
 
     public void GenerateItemsChest()
     {
         items.Add(new Item {Name = "Note", Id = 1, sprite = sprites[0], Type = "Quest"});
         items.Add(new Item {Name = "Sword", Id = 2, sprite = sprites[1], Type = "Weapon"});
         items.Add(new Item {Name = "Shield", Id = 3, sprite = sprites[2], Type = "Armor"});
         items.Add(new Item {Name = "Spear", Id = 4, sprite = sprites[3], Type = "Weapon"});
         items.Add(new Item {Name = "PoleArm", Id = 5, sprite = sprites[4], Type = "Weapon"});
         //Printing Name ;)
         foreach (var item in items)
         {
             Debug.Log(item.Name);
         }
     }
 
     [Serializable]
     public class Item
     {
         public string Name { get; set; }
 
         public int Rarity { get; set; }
 
         public int Id { get; set; }
 
         public Sprite sprite { get; set; }
 
         public string Type { get; set; }
     }
 }
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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

NullReference with trigger C# ? 1 Answer

Null Reference Excepting :Object reference not set to an instance of object while changing text of 3D text 2 Answers

NullReference on textfield 1 Answer

Can I Ignore Null Reference Exceptions? ( bug? ) 3 Answers

itween example work well on unity3d while NullReferenceException on android 0 Answers


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