-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlayerInventory.cs
More file actions
72 lines (54 loc) · 1.74 KB
/
PlayerInventory.cs
File metadata and controls
72 lines (54 loc) · 1.74 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using UnityEngine;
public class PlayerInventory : MonoBehaviour
{
public static PlayerInventory Instance;
public int inventorySize;
public int selectedSlot;
public ItemSO currentHeldItem;
[SerializeField] private Transform handTransform;
[SerializeField] private ItemSO[] playerInventory;
private GameObject _displayedItem;
private void Awake()
{
if (Instance == null)
Instance = this;
playerInventory = new ItemSO[inventorySize];
}
public bool TryAddItem(ItemSO item)
{
int emptySlot = FindEmptySlot();
if (emptySlot == -1) return false;
playerInventory[emptySlot] = item;
UpdateHeldItem();
return true;
}
public bool TryRemoveItem(ItemSO item)
{
if(playerInventory[selectedSlot] == null) return false;
playerInventory[selectedSlot] = null;
UpdateHeldItem();
return true;
}
public void SelectSlot(int slotIndex)
{
if(slotIndex < 0 || slotIndex >= playerInventory.Length) return;
selectedSlot = slotIndex;
UpdateHeldItem();
}
private int FindEmptySlot()
{
for (int i = 0; i < playerInventory.Length; i++)
{
if (playerInventory[i] == null)
return i;
}
return -1;
}
private void UpdateHeldItem()
{
if(_displayedItem != null) Destroy(_displayedItem);
currentHeldItem = playerInventory[selectedSlot];
if (currentHeldItem == null) return;
_displayedItem = Instantiate(currentHeldItem.itemPrefab, handTransform);
}
}