Item.cs
1 2 3 4 5 6 7 8 9 10 11 12 | [System.Serializable] public class Item { public string name; public int count; public Item( string itemName, int itemCount) { name = itemName; count = itemCount; } } |
Inventory.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | using System.Collections; using System.Collections.Generic; using UnityEngine; public class Inventory : MonoBehaviour { public static Inventory instance; public List<Item> items = new List<Item>(); void Awake() { if (instance != null ) Destroy(gameObject); else instance = this ; } public void AddItem(Item itemToAdd) { bool itemExists = false ; foreach (Item item in items) { if (item.name == itemToAdd.name) { item.count += itemToAdd.count; itemExists = true ; break ; } } if (!itemExists) { items.Add(itemToAdd); } Debug.Log(itemToAdd.count + " " + itemToAdd.name + "added to inventory." ); } public void RemoveItem(Item itemToRemove) { foreach ( var item in items) { if (item.name == itemToRemove.name) { item.count -= itemToRemove.count; if (item.count <= 0) { items.Remove(itemToRemove); } break ; } } Debug.Log(itemToRemove.count + " " + itemToRemove.name + "removed from inventory." ); } } |
Pickup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | using System.Collections; using System.Collections.Generic; using UnityEngine; public class Pickup : MonoBehaviour { public Item item = new Item( "Item Name" , 1); void OnTriggerEnter(Collider other) { if (other.CompareTag( "Player" )) { Inventory.instance.AddItem(item); Destroy(gameObject); } } } |