• 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 ikechukwuanude · Jun 06, 2018 at 04:32 PM · inventoryinventory systemiteminteractiveitem pickup

How to add item to my inventory when I pick them up?

I'm somewhat new to Unity and game development but I keep getting t$$anonymous$$s error:

 NullReferenceException: Object reference not set to an instance of an object
 HUD.InventoryScript_ItemAdded (System.Object sender, .InventoryEventArgs e) (at Assets/HUD.cs:21)
 inventory.AddItem (IInventoryItem item) (at Assets/Scripts/inventory.cs:42)
 collider.OnCollisionEnter (UnityEngine.Collision col) (at Assets/Scripts/collider.cs:38)

Usually when I get a NullReferenceException, the fixes is dragging in the object that a script is referring to. From what I can see here, the collider (w$$anonymous$$ch is on the player) is detecting the collision between the player and the item. It sent the information of collision object to the inventory class w$$anonymous$$ch adds the object to the List of inventory items. From here t$$anonymous$$ngs get a bit murky as it throws the error in the HUD.InventoryScript_ItemAdded method.

Here is the HUD.cs script

 using UnityEngine;
 using UnityEngine.UI;

 public class HUD : MonoBehaviour {

     public inventory Inventory;


     // Use t$$anonymous$$s for initialization
     void Start () {

         Inventory.ItemAdded += InventoryScript_ItemAdded;
     
     }

     private void InventoryScript_ItemAdded(object sender, InventoryEventArgs e)
     {
         Transform inventoryPanel = transform.Find("InventoryPanel");
         foreach(Transform slot in inventoryPanel)
         {

             //Border to image
             Image image = slot.GetC$$anonymous$$ld(0).GetC$$anonymous$$ld(0).GetComponent<Image>();

             //We found the empty slot
             if (!image.enabled)
             {
                 image.enabled = true;
                 image.sprite = e.Item.Image;

                 //TODO: Store reference to the item

                 break; //what does t$$anonymous$$s do?
         }
     }
  }
 

 

 // Update is called once per frame
 void Update () {
     
 }
 }  

T$$anonymous$$s is the inventory script

 public class inventory : MonoBehaviour {

 //fixed number of slots
 private const int SLOTS = 10;

 //creates an arraylist of inventory items
 private List<IInventoryItem> mItems = new List<IInventoryItem>();

 //handles event?
 public event EventHandler<InventoryEventArgs> ItemAdded;

 //adding item method
 public void AddItem(IInventoryItem item)
 {

     //if there are free slots available
     if (mItems.Count < SLOTS)
     {

         //collide with item
         Collider collider = (item as MonoBehaviour).GetComponent<Collider>();

         
         if (collider.enabled)
         {
             //if the collider of the object is enabled turn it off
             collider.enabled = false;

             //add to array list
             mItems.Add(item);

             item.OnPickup();

             //all subscribers of event are notfified?
             if(ItemAdded != null)
             {
                 ItemAdded(t$$anonymous$$s,new InventoryEventArgs(item));
             }
         }
     }
 }
 }

And finally t$$anonymous$$s is the collider script I put on my player

 public class collider : MonoBehaviour
 {
     public inventory Inventory;
     //public GameObject pickupEffect;
     public gun g;

     void OnTriggerEnter(Collider other)
 {
     
     if(other.gameObject.tag == "item")
     {
         Debug.Log("You Hit an item");
         Destroy(other.gameObject);

     }

     if(other.gameObject.tag == "ammo")
     {
         Debug.Log("Picked up ammo");
         Destroy(other.gameObject);
         g.ammo += 30;
     }
 }

 void OnCollisionEnter(Collision col)
 {
     
     if(col.gameObject.tag == "collectable")
     {
         Debug.Log("T$$anonymous$$s object is collectable");
         IInventoryItem item = col.gameObject.GetComponent<IInventoryItem>();
         if (item != null)
         {
             Inventory.AddItem(item);
             Debug.Log("Collided with an inventory item");
         }
     }

    
 }

 /*
  * 
 //check if item collided with has an inventory item interface
 private void OnControllerColliderHit(ControllerColliderHit $$anonymous$$t)
 {
     Debug.Log("Collided with an inventory item");
     IInventoryItem item = $$anonymous$$t.collider.GetComponent<IInventoryItem>();
     if(item != null)
     {
         Inventory.AddItem(item);

         Debug.Log("Collided with an inventory item");
     }
 }

 */

}

Sorry if the code is not formatted correctly but the system for creating code in t$$anonymous$$s forum seems to be a bit tedious because you have to space 4 times for each line.

Anyway, why am I getting t$$anonymous$$s error and how could I fix it w$$anonymous$$le implementing t$$anonymous$$s code?

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 Horschty · Jun 06, 2018 at 07:26 PM

According to your error message "(at Assets/HUD.cs:21)" t$$anonymous$$s seems to be the problem:

 Image image = slot.GetC$$anonymous$$ld(0).GetC$$anonymous$$ld(0).GetComponent<Image>();

GetC$$anonymous$$ld could return null if there are no c$$anonymous$$ldren. Try to do it in stages to better be able to debug it. Set a breakpoint and step through and check the return values.

 var c$$anonymous$$ld1 = slot.GetC$$anonymous$$ld(0);
 var c$$anonymous$$ld2 = c$$anonymous$$ld1.GetC$$anonymous$$ld(0);
 var image = c$$anonymous$$ld2.GetComponent<Image>();

But there's probably a better way to get access to the Image component. Maybe GetComponentInC$$anonymous$$ldren<Image>() if there is only one Image component in the descendants $$anonymous$$erarchy. Or give the GameObject with the Image component on it a name and use

 var gameObj = slot.find("ImageContainer");
 Image image;
 if(gameObj != null) {
   image = gameObj.GetComponent<Image>();
 }



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

84 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Inventory AddItem help 1 Answer

Hey, i can't figure out, what my problem is. I want to Add something into the player's Inventory, but before that it should check, whether there is an Item with the same name in it, or not and if yes, if the maxAmount for that slot is reached. 0 Answers

How i can make a script-made button interactable? 0 Answers

inventory system: drop item with mouseclick 1 Answer

How to combine items in inventory with words 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