Scriptum/Assets/Scripts/Objects' Scripts/Chest.cs
2022-05-29 12:33:43 +02:00

77 lines
2.0 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Chest : MonoBehaviour
{
[SerializeField] public GameObject chest;
[SerializeField] public GameObject chestPanel;
[SerializeField] public List<Item> itemsList = new List<Item>();
private GameObject dynamicPanel; // UI elemend created during script work
bool isOpen = false;
bool isTrigerred = false;
// Start is called before the first frame update
void Start()
{
chest = gameObject; // set object on current GameObject
}
// Update is called once per frame
void Update()
{
if (chestPanel && isTrigerred && !isOpen) // we can open chest only when its closed
{
if (Input.GetKeyDown(KeyCode.E))
{
OpenChest();
}
}
}
void OnTriggerExit2D(Collider2D collision)
{
if (chestPanel != null)
{
CloseChest();
}
isTrigerred = false;
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Player")
{
isTrigerred = true;
}
}
public void OpenChest()
{
GameObject globalGUI = GameObject.FindGameObjectsWithTag("GUI")[0];
if(globalGUI)
{
dynamicPanel = Instantiate(chestPanel, chestPanel.transform.position, Quaternion.identity, globalGUI.transform); // 4'th arg allow set object as child
dynamicPanel.transform.localPosition = chestPanel.transform.position; // prevent overwritten position by... environment???
dynamicPanel.GetComponent<ChestPanelController>().SetupChest(gameObject, itemsList); // bind pandel to current chest
isOpen = true;
} else {
Debug.Log("Can't find global GUI object!!!");
}
}
public void CloseChest()
{
Destroy(dynamicPanel); // destroy object from scene
isOpen = false;
}
}