90 lines
2.5 KiB
C#
90 lines
2.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using TMPro;
|
|
using UnityEngine;
|
|
|
|
public class FloatingTextSpawner {
|
|
private static GameObject GameObjectContainer = new GameObject($"Floating Text Container");
|
|
private Transform Transform;
|
|
private float YOffset;
|
|
private List<Transform> TextList = new List<Transform>();
|
|
|
|
public FloatingTextSpawner(Transform transform, float yOffset) {
|
|
Transform = transform;
|
|
YOffset = yOffset;
|
|
}
|
|
|
|
public void SpawnFloatingText(string message, Color color, float duration = 1.5f) {
|
|
try {
|
|
|
|
GameObject textObj = new GameObject("FloatingText");
|
|
textObj.transform.position = Transform.position + new Vector3(0, 1, 1); // offset above character
|
|
|
|
TextMeshPro text = textObj.AddComponent<TextMeshPro>();
|
|
text.text = message;
|
|
//text.size = 0.2f;
|
|
text.fontSize = 14;
|
|
text.fontStyle = FontStyles.Bold;
|
|
text.color = color;
|
|
text.alignment = TextAlignmentOptions.Center;
|
|
//text.anchor = TextAnchor.MiddleCenter;
|
|
text.outlineColor = Color.black;
|
|
text.outlineWidth = 0.4f;
|
|
|
|
Renderer renderer = textObj.GetComponent<Renderer>();
|
|
renderer.sortingLayerName = "UI";
|
|
renderer.sortingOrder = 0;
|
|
|
|
textObj.AddComponent<FloatingText>().Init(duration, ref TextList, YOffset);
|
|
UnityEngine.Object.Instantiate(textObj, GameObjectContainer.transform);
|
|
} catch (Exception e) { }
|
|
}
|
|
}
|
|
|
|
|
|
public class FloatingText : MonoBehaviour {
|
|
private float lifetime;
|
|
private float speed = 1f;
|
|
private Color originalColor;
|
|
private TextMeshPro text;
|
|
|
|
|
|
public void Init(float duration, ref List<Transform> textList, float yOffset) {
|
|
try {
|
|
lifetime = duration;
|
|
text = GetComponent<TextMeshPro>();
|
|
originalColor = text.color;
|
|
|
|
//for (int i = textList.Count - 1; i >= 0; i--) {
|
|
// if (textList[i] == null)
|
|
// textList.RemoveAt(i);
|
|
// else
|
|
// textList[i].position += Vector3.up * yOffset;
|
|
//}
|
|
|
|
//textList.Add(this.transform);
|
|
} catch (Exception e) { }
|
|
}
|
|
|
|
void Update() {
|
|
try {
|
|
|
|
transform.position += Vector3.up * speed * Time.deltaTime;
|
|
|
|
lifetime -= Time.deltaTime;
|
|
if (lifetime <= 0) {
|
|
Destroy(gameObject);
|
|
} else {
|
|
float alpha = Mathf.Clamp01(lifetime / 1.5f);
|
|
text.color = new Color(originalColor.r, originalColor.g, originalColor.b, alpha);
|
|
}
|
|
} catch (Exception e) { }
|
|
|
|
}
|
|
}
|
|
|
|
|