using System.Collections;
using System.Collections.Generic;
using UnityEditor.UI;
using UnityEngine;
using TMPro;
/// <summary>
/// 위로 천천히 이동하며 사라지는 플로팅 텍스트
/// </summary>
public class FloatingText : MonoBehaviour
{
[Header("References")]
[SerializeField] private TextMeshProUGUI _text;
private RectTransform _rect;
[Header("Motion")]
[SerializeField] private float _lifeTime = 1.5f;
[SerializeField] private float _riseSpeed = 40f;
[SerializeField] private float _fadePerSec = 1.0f;
private float _elapsed = 0f;
void Awake()
{
_rect = GetComponent<RectTransform>();
if(_text == null)
{
_text = GetComponentInChildren<TextMeshProUGUI>();
}
}
public void Setup(string message, Color color, Vector2 startScreenPos)
{
if(_text != null)
{
_text.text = message;
_text.color = color;
}
_rect.position = startScreenPos;
}
void Update()
{
_rect.anchoredPosition += Vector2.up * _riseSpeed * Time.deltaTime;
if(_text != null)
{
Color c = _text.color;
c.a -= _fadePerSec * Time.deltaTime;
c.a = Mathf.Clamp01(c.a);
_text.color = c;
}
_elapsed += Time.deltaTime;
if(_elapsed >= _lifeTime)
{
Destroy(gameObject);
}
}
}
전체 흐름
- Awake
_rect 캐싱
_text 가 비면 GetComponentInChildrec<TextMeshProUGUI>() 를 가져온다 - Setup(message , color , startScreenPos)
텍스트 내용과 색 지정
시작 위치를 startScreenPos 로 배치 ( 좌표계 이슈 중요 ) - Update
anchoredPosition 을 위로 이동
텍스트 색상의 알파 감소 ( c.a )
a 는 alpha , 텍스트의 투명도 조절
Clamp01 로 0 ~ 1 고정 ( 음수를 방지하려고 )
_elapsed 누적 후 _lifeTime 지났으면 Destroy(gameObject)
좌표계 포인트
- Setup 에서 _rect.position = startScreenPos ( 월드 좌표 ) 로 배치
- Update 에서 _rect.anchoredPosition ( 로컬 / 앵커 기준 ) 으로 이동
- 서로 다른 좌표축을 섞어 쓰는 셈이라 상황에 따라 시작점이 어긋날 수 있다.
핵심 필드
- TextMeshProUGUI _text : 글자 렌더링 컴포넌트
- RectTransform _rect : UI 좌표를 다루는 핵심 ( 앵커 / 피벗 기반 )
- _riseSpeed : 캔버스 좌표계의 픽셀 / 초 속도
- _fadePerSec : 초당 알바 감소량
- _lifeTime : 객체 생존 시간