116 lines
2.9 KiB
C#
116 lines
2.9 KiB
C#
using System;
|
|
using Items;
|
|
using Terrain;
|
|
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
namespace UI {
|
|
public class UIItemSlot : MonoBehaviour {
|
|
|
|
public bool linked;
|
|
public ItemSlot itemSlot;
|
|
public Image slotImage;
|
|
public Image slotIcon;
|
|
public Text slotAmount;
|
|
public World world;
|
|
|
|
private void Awake() {
|
|
world = GameObject.Find("World").GetComponent<World>();
|
|
}
|
|
|
|
public bool HasItem => itemSlot?.HasItem == true;
|
|
|
|
public void Link(in ItemSlot slot) {
|
|
itemSlot = slot;
|
|
linked = true;
|
|
itemSlot.LinkUISlot(this);
|
|
UpdateSlot();
|
|
}
|
|
|
|
public void Unlink() {
|
|
itemSlot.UnlinkUISlot();
|
|
itemSlot = null;
|
|
linked = false;
|
|
UpdateSlot();
|
|
}
|
|
|
|
public void UpdateSlot() {
|
|
if (HasItem) {
|
|
slotIcon.sprite = world.blockTypes[itemSlot.Stack.Block].icon;
|
|
slotAmount.text = itemSlot.Stack.Amount.ToString();
|
|
slotIcon.enabled = true;
|
|
slotAmount.enabled = true;
|
|
} else Clear();
|
|
}
|
|
|
|
private void Clear() {
|
|
slotIcon.enabled = false;
|
|
slotAmount.enabled = false;
|
|
slotIcon.sprite = null;
|
|
slotAmount.text = null;
|
|
}
|
|
|
|
private void OnDestroy() {
|
|
if (linked)
|
|
itemSlot.UnlinkUISlot();
|
|
}
|
|
}
|
|
|
|
[Serializable]
|
|
public class ItemSlot {
|
|
public ItemStack Stack;
|
|
private UIItemSlot _slot;
|
|
|
|
public bool creative;
|
|
|
|
public ItemSlot(in UIItemSlot slot) {
|
|
_slot = slot;
|
|
_slot.Link(this);
|
|
}
|
|
|
|
public ItemSlot(in UIItemSlot slot, in ItemStack stack) {
|
|
Stack = stack;
|
|
_slot = slot;
|
|
_slot.Link(this);
|
|
}
|
|
|
|
public void LinkUISlot(in UIItemSlot slot) => _slot = slot;
|
|
public void UnlinkUISlot() => _slot = null;
|
|
|
|
public void EmptySlot() {
|
|
Stack = null;
|
|
if (_slot != null)
|
|
_slot.UpdateSlot();
|
|
}
|
|
|
|
public int Take(int amount) {
|
|
if (amount > Stack.Amount) {
|
|
int result = Stack.Amount;
|
|
EmptySlot();
|
|
return result;
|
|
}
|
|
|
|
if (amount < Stack.Amount) {
|
|
Stack.Amount -= amount;
|
|
if (_slot != null) _slot.UpdateSlot();
|
|
return amount;
|
|
}
|
|
|
|
EmptySlot();
|
|
return amount;
|
|
}
|
|
|
|
public ItemStack TakeAll() {
|
|
ItemStack result = new ItemStack(Stack.Block, Stack.Amount);
|
|
EmptySlot();
|
|
return result;
|
|
}
|
|
|
|
public void InsertStack(in ItemStack stack) {
|
|
Stack = stack;
|
|
if (_slot != null) _slot.UpdateSlot();
|
|
}
|
|
|
|
public bool HasItem => Stack != null;
|
|
}
|
|
} |