Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- using System.Collections.Generic;
- using Assets.Scripts;
- using UnityEngine.UI;
- using UnityEngine.Events;
- public class InventoryHandler : MonoBehaviour {
- public List<InventoryItem> _inventory = new List<InventoryItem>();
- public ObjectInteractor interactor;
- public Font font;
- private List<GameObject> _items = new List<GameObject>();
- private List<Text> _text = new List<Text>();
- // Use this for initialization
- void Start() {
- interactor = FindObjectOfType<ObjectInteractor>();
- }
- // Update is called once per frame
- void FixedUpdate() {
- if (_inventory.Count != _items.Count) {
- Refresh();
- }
- for (int i = 0; i < _text.Count; i++) {
- if (_text[i].text != _inventory[i].InventoryName) {
- Refresh();
- break;
- }
- }
- }
- public void Refresh() {
- for (int i = _items.Count - 1; i >= 0; i--) {
- if (_items[i] != null) {
- Destroy(_items[i]);
- Destroy(_text[i]);
- }
- }
- _items.Clear();
- _text.Clear();
- int count = 0;
- for (int y = 0; y < Mathf.CeilToInt((float) _inventory.Count / 4f); y++) {
- for (int x = 0; x < 4; x++) {
- if (count < _inventory.Count) {
- GameObject item = new GameObject("button", typeof(RectTransform));
- Button button = item.AddComponent<Button>();
- item.AddComponent<CanvasRenderer>();
- Image image = item.AddComponent<Image>();
- item.transform.SetParent(transform, false);
- image.sprite = Sprite.Create(_inventory[count].InventoryImage, new Rect(0, 0, 100, 100), new Vector2(0, 0));
- image.rectTransform.sizeDelta = new Vector2(50, 50);
- image.rectTransform.anchoredPosition = new Vector2(x * 50 - 75, -y * 50 + 150);
- InventoryItem currentInventoryItem = _inventory[count];
- UnityAction action = new UnityAction(delegate {
- if (_inventory.Count > 0) {
- InventoryItem inventoryItem = currentInventoryItem;
- switch (inventoryItem.Type) {
- case InventoryItem.CategoryType.Equipment:
- interactor.currentItem = inventoryItem;
- interactor.lockInventory = false;
- FindObjectOfType<Canvas>().enabled = false;
- break;
- case InventoryItem.CategoryType.Paper:
- inventoryItem.Use();
- break;
- case InventoryItem.CategoryType.Item:
- inventoryItem.Use();
- break;
- }
- }
- });
- button.onClick.AddListener(action);
- GameObject textItem = new GameObject("text", typeof(RectTransform));
- Text text = textItem.AddComponent<Text>();
- textItem.transform.SetParent(button.transform, false);
- text.rectTransform.anchorMax = new Vector2(1, 1);
- text.rectTransform.anchorMin = new Vector2(0, 0);
- text.rectTransform.sizeDelta = new Vector2(5, 0);
- text.rectTransform.anchoredPosition = new Vector2(2f, 0);
- text.text = currentInventoryItem.InventoryName;
- text.font = font;
- text.color = Color.black;
- text.fontSize = 12;
- _text.Add(text);
- _items.Add(item);
- count++;
- } else {
- break;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment