• 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
Question by Lilconiglio · Jan 23, 2017 at 03:50 PM · databasejsoninventory systemitemsrpg-game

How to add item to inventory with these scripts

Hi, I've been pulling my hair out. How would I go to add a GameObject (i.e. loot or similar) item to the inventory when clicked upon using the scripts below? I've tried everything I could think of but nothing seem to work. I'm using a json datafile to contain my item database (each item has an id, title etc) and it's retrieved with the inventory and itemDatabase scripts below. Thanks

Script that has the ray cast

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class WorldInteraction : MonoBehaviour {
     UnityEngine.AI.NavMeshAgent playerAgent;
 
     void Start(){
 
         playerAgent = GetComponent<UnityEngine.AI.NavMeshAgent> ();
     }
 
 
     void Update(){
         if (Input.GetMouseButtonDown (0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()) {
             GetInteraction ();
 
         }
 
     }
 
     void GetInteraction(){
         Ray interactionRay = Camera.main.ScreenPointToRay (Input.mousePosition); // Set up initial ray (not yet casting to anything)
         RaycastHit interactionInfo; // This will be used to store the ray's hit information
         if (Physics.Raycast (interactionRay, out interactionInfo, Mathf.Infinity)) { // if the ray Interactionray hits anything, store the info into interactionInfo, mathf.infinity = length of ray
             GameObject interactedObject = interactionInfo.collider.gameObject; // make new GameObject "interactedObject" the gameObject of the collider the ray hit
             if (interactedObject.tag == "Interactable Object") {
 
                 interactedObject.GetComponent<Interactable> ().MoveToInteraction(playerAgent);
 
             } else {
                 playerAgent.stoppingDistance = 0;
                 playerAgent.destination = interactionInfo.point;
             }
         }
 
     }
 }

Script that manages the interactions

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.AI;
 
 public class Interactable : MonoBehaviour {
     [HideInInspector]
     public NavMeshAgent playerAgent;
     private bool hasInteracted;
 
     public virtual void MoveToInteraction(NavMeshAgent playerAgent){
         hasInteracted = false;
         this.playerAgent = playerAgent;
         playerAgent.stoppingDistance = 4f;
         playerAgent.destination = this.transform.position;
 
     }
 
     void Update(){
         if (playerAgent != null && !playerAgent.pathPending && !hasInteracted) {
             if (playerAgent.remainingDistance <= playerAgent.stoppingDistance) {
                 Interact ();
                 hasInteracted = true;
             }
 
         }
 
     }
 
     public virtual void Interact(){
         Debug.Log ("Interacting with base class.");
 
     }
 }
 

Inventory Script

 using System.Collections;
 using System.Collections.Generic;
 using System.IO;
 using UnityEngine;
 using UnityEngine.UI;
 using LitJson;
 
 public class Inventory : MonoBehaviour {
 
     GameObject inventoryPanel;
     GameObject slotPanel;
     ItemDatabase database;
     public GameObject inventorySlot;
     public GameObject inventoryItem;
     int slotAmount;
 
 
 
     public List<Item> items = new List<Item>();
     public List<GameObject> slots = new List<GameObject>();
 
 
 
     void Start(){
         database = GetComponent<ItemDatabase> ();
         slotAmount = 16;
         inventoryPanel = GameObject.Find ("Bag");
         slotPanel = inventoryPanel.transform.FindChild ("Slots").gameObject;
         for (int i = 0; i < slotAmount; i++) {
             items.Add(new Item());
             slots.Add (Instantiate (inventorySlot));
             slots[i].transform.SetParent(slotPanel.transform);
             inventorySlot.name = "Slot " + i ;
 
         }
 
 
         AddItem (0);
         AddItem (0);
         AddItem (0);
         AddItem (1);
         AddItem (1);
 
 
 
     }
 
     public void AddItem(int id){
         Item itemToAdd = database.FetchItemByID (id);
         if (itemToAdd.Stackable && CheckIfItemInInventory (itemToAdd)) {
 
             for (int i = 0; i < items.Count; i++) {
                 if (items [i].ID == id) {
                     ItemData data = slots [i].transform.GetChild (0).GetComponent<ItemData> ();
                     data.amount++;
                     data.transform.GetChild (0).GetComponent<Text> ().fontSize = 20;
                     data.transform.GetChild (0).GetComponent<Text> ().text = data.amount.ToString();
                     RectTransform textScale = data.transform.GetChild (0).GetComponent<RectTransform> ();
                     textScale.anchoredPosition = new Vector2 (-7, 10);
                     textScale.transform.localScale += new Vector3 (-0.15f, -0.15f, 1);
                 
 
                     break;
 
                 }
             }
         } else {
             
         for (int i = 0; i < items.Count; i++) {
             if (items[i].ID == -1){
                 
                 items [i] = itemToAdd;
                 GameObject ItemObject = Instantiate (inventoryItem);
                 ItemObject.transform.SetParent (slots[i].transform);
                 ItemObject.transform.position = Vector2.zero;
                 ItemObject.GetComponent<Image> ().sprite = itemToAdd.Sprite;
                 ItemObject.name = itemToAdd.Title;
                 ItemData data = slots[i].transform.GetChild (0).GetComponent<ItemData> ();
                 data.amount = 1;
 
                 break;
             }
 
         }
 
     }
 }
 
     bool CheckIfItemInInventory (Item item){
 
             for (int i = 0; i < items.Count; i++)
 
             if (items [i].ID == item.ID)
                 return true;
             
         return false;
 
     }
 }
 


Item Database script

 using System.Collections;
 using System.Collections.Generic;
 using System.IO;
 using UnityEngine;
 using LitJson;
 
 public class ItemDatabase : MonoBehaviour {
     private List<Item> database = new List<Item>();
     private JsonData itemData;
 
     void Start(){
 
         itemData = JsonMapper.ToObject(File.ReadAllText(Application.dataPath + "/StreamingAssets/Items.json"));
 
         ConstructItemDatabase();
 
         Debug.Log (FetchItemByID(0).Description);
 
     }
     public Item FetchItemByID(int id){
         for (int i = 0; i < database.Count; i++) 
             if (database[i].ID == id)
                 return database[i];
         return null;
     }
 
     void ConstructItemDatabase(){
 
         for (int i = 0; i < itemData.Count; i++){
 
             database.Add(new Item((int)itemData[i]["id"], itemData[i]["title"].ToString(), (int)itemData[i]["value"], (int)itemData[i]["resellvalue"], itemData[i]["description"].ToString(), (bool)itemData[i]["stackable"], itemData[i]["slug"].ToString()));
         }
     }
 
 }
 
 public class Item {
 
     public int ID { get; set;}
     public string Title { get; set;}
     public int Value { get; set;}
     public int Resellvalue { get; set;}
     public string Description { get; set;}
     public bool Stackable { get; set;}
     public string Slug { get; set;}
     public Sprite Sprite { get; set;}
 
     public Item(int id, string title, int value, int resellvalue, string description, bool stackable, string slug){
         
         this.ID = id;
         this.Title = title;
         this.Value = value;
         this.Resellvalue = resellvalue;
         this.Description = description;
         this.Stackable = stackable;
         this.Slug = slug;
         this.Sprite = Resources.Load<Sprite> ("FantasyIcon/512/" + slug);
 
     }
 
     public Item(){
 
         this.ID = -1;
 
     }
 }





Comment

People who like this

0 Show 0
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

0 Replies

· Add your reply
  • Sort: 

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

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Whats the best option for an item database for a single player game 2 Answers

Unity Inventory Database ID Error 1 Answer

How do delete the lowest value on my list? 0 Answers

Classifying item types without inheritance 0 Answers

Item is missing in inventory slot after i pick up and delete the item. C# 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