生成Unity文字渐变淡入加打字机效果的代码
时间: 2023-04-04 12:03:21 浏览: 267
您好,以下是生成Unity文字渐变淡入加打字机效果的代码:
using UnityEngine;
using UnityEngine.UI;
public class TextEffect : MonoBehaviour
{
public float fadeInTime = 1f; // 渐入时间
public float typeTime = 1f; // 打字机效果时间
public float delayTime = 0.5f; // 延迟时间
private Text text;
private Color originalColor;
private float timer = 0f;
private bool isFadingIn = true;
private bool isTyping = false;
void Start()
{
text = GetComponent<Text>();
originalColor = text.color;
text.color = new Color(originalColor.r, originalColor.g, originalColor.b, 0f); // 初始透明度为0
}
void Update()
{
if (isFadingIn)
{
timer += Time.deltaTime;
float alpha = Mathf.Lerp(0f, originalColor.a, timer / fadeInTime); // 渐入
text.color = new Color(originalColor.r, originalColor.g, originalColor.b, alpha);
if (timer >= fadeInTime)
{
isFadingIn = false;
timer = 0f;
isTyping = true;
}
}
else if (isTyping)
{
timer += Time.deltaTime;
int visibleCount = (int)Mathf.Lerp(0, text.text.Length, timer / typeTime); // 打字机效果
text.maxVisibleCharacters = visibleCount;
if (visibleCount >= text.text.Length)
{
isTyping = false;
timer = 0f;
}
}
else
{
timer += Time.deltaTime;
if (timer >= delayTime) // 延迟
{
timer = 0f;
isFadingIn = true;
text.color = new Color(originalColor.r, originalColor.g, originalColor.b, 0f);
text.maxVisibleCharacters = 0;
}
}
}
}
阅读全文