using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; public enum FloatingLabelDirection { Up, Down } public class FloatingLabel : MonoBehaviour { [SerializeField] private TextMeshProUGUI text; [SerializeField] private Sprite sprite; [SerializeField] private float positionOffset = 1; [SerializeField] private float speed = 2; private CanvasGroup canvasGroup; private FloatingLabelDirection direction; public void Spawn(string text, FloatingLabelDirection direction, float positionOffset = 1) { canvasGroup = GetComponent(); canvasGroup.alpha = 0; this.text.text = text; this.direction = direction; this.positionOffset = positionOffset; StopAllCoroutines(); StartCoroutine(Appear()); } IEnumerator Appear() { while (canvasGroup.alpha < 1) { canvasGroup.alpha += Time.deltaTime * speed; transform.position += (direction == FloatingLabelDirection.Up ? 1 : -1) * positionOffset * speed * Time.deltaTime * Vector3.up; yield return null; } } public void Despawn() { StopAllCoroutines(); StartCoroutine(Disappear()); } IEnumerator Disappear() { while (canvasGroup.alpha > 0) { canvasGroup.alpha -= Time.deltaTime * speed; transform.position += (direction == FloatingLabelDirection.Up ? 1 : -1) * positionOffset * Time.deltaTime * Vector3.up * speed; yield return null; } Destroy(gameObject); } }