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 /
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 this 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 (which 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 which adds the object to the List of inventory items. From here things 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 this 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.GetChild(0).GetChild(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 this do?
         }
     }
  }
 

 

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

This 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(this,new InventoryEventArgs(item));
             }
         }
     }
 }
 }

And finally this 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("This 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 hit)
 {
     Debug.Log("Collided with an inventory item");
     IInventoryItem item = hit.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 this forum seems to be a bit tedious because you have to space 4 times for each line.

Anyway, why am I getting this error and how could I fix it while implementing this 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)" this seems to be the problem:

 Image image = slot.GetChild(0).GetChild(0).GetComponent<Image>();

GetChild could return null if there are no children. 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 child1 = slot.GetChild(0);
 var child2 = child1.GetChild(0);
 var image = child2.GetComponent<Image>();

But there's probably a better way to get access to the Image component. Maybe GetComponentInChildren<Image>() if there is only one Image component in the descendants hierarchy. 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.

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