using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using TMPro;

public static class GameObjectTextExtension
{
    public static FloatingText FloatText(this GameObject o, string s)
    {
        return FloatingTextManager.Instance().CreateFloatingText(o, s);
    }
}

public class FloatingTextManager : MonoBehaviour {

    public GameObject Prefab = null;
    public float DistanceFromCamera = 5.0f;

    public FloatingText CreateFloatingText(GameObject obj, string s)
    {
        GameObject ftObj = null;
        if (obj != null)
        {
            // Offset the text towards the camera
            Vector3 fromCamera = obj.transform.position - Camera.main.transform.position;
            Vector3 spawnPoint = Camera.main.transform.position + fromCamera.normalized * DistanceFromCamera;

            ftObj = GameObject.Instantiate(Prefab, spawnPoint, Prefab.transform.localRotation) as GameObject;

            ftObj.transform.SetParent(transform, false);

            ftObj.GetComponentInChildren<TextMeshPro>().text = s;
        }

        FloatingText result = ftObj.GetComponent<FloatingText>();

        return result;

    }
    private static FloatingTextManager _instance;
    public static FloatingTextManager Instance()
    {
        if (_instance == null)
        {
            GameObject newObj = new GameObject("FloatingTextManager");
            _instance = newObj.AddComponent<FloatingTextManager>();
            _instance.Prefab = Resources.Load("FloatingText") as GameObject;
        }

        return _instance;
    }

    public FloatingTextManager()
    {
        if (_instance == null)
        {
            _instance = this;
        }
    }

    void Awake()
    {
        if (_instance == null)
        {
            _instance = this;
            DontDestroyOnLoad(this);
        }
        else
        {
            if (this != _instance)
                Destroy(this.gameObject);
        }
    }

    // Use this for initialization
    void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}
