Encounter / Assets / Scripts / GUIHandlers / SkillGUIManager.cs
SkillGUIManager.cs
Raw
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

/// <summary>
/// Handles injecting and instancing the Skill GUI Helper system
/// </summary>
public class SkillGUIManager : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
    private Transform instanceLocation;

    private Vector2 offset;

    private GameObject skillGUIHelper;
    private GameObject instancedHelper;

    private SkillButton attachedButton;
    private SkillSO skillData;

    private void Awake()
    {
        skillGUIHelper = Resources.Load<GameObject>("Prefabs/SkillGUIHelper");
        attachedButton = GetComponent<SkillButton>();
        
        // Get the parent of the skill button field to prevent the arrows from overshadowing the helpful UI
        instanceLocation = transform.parent.parent;
    }

    private void Start()
    {
        skillData = attachedButton.GatherData();

        DetermineOffset();
    }

    private void DetermineOffset()
    {
        if (attachedButton.IsLeft && attachedButton.IsTop)
            offset = new Vector2(3.25f, -1.55f);
        else if (attachedButton.IsLeft && attachedButton.IsBottom)
            offset = new Vector2(3.25f, 1.55f);
        else if (attachedButton.IsRight && attachedButton.IsTop)
            offset = new Vector2(-3.25f, -1.55f);
        else if (attachedButton.IsRight && attachedButton.IsBottom)
            offset = new Vector2(-3.25f, 1.55f);
        else
            throw new InvalidOperationException();
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        if (instancedHelper == null)
        {
            Vector2 pos = transform.position;
            pos.x += offset.x;

            // Calculates where in the screen the aspect is so the helper instance doesn't transpose off the screen
            if (instanceLocation.GetComponent<RectTransform>().rect.height < pos.y + offset.y)
                pos.y -= offset.y;
            else
                pos.y += offset.y;

            instancedHelper = Instantiate(skillGUIHelper, pos, Quaternion.identity, instanceLocation);
            instancedHelper.GetComponent<SkillGUI>().InjectData(skillData);
        }
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        if (instancedHelper != null)
            DestroyImmediate(instancedHelper);
    }

    private void OnDisable()
    {
        if (instancedHelper != null)
            DestroyImmediate(instancedHelper);
    }
}