unity怎么用代码渐隐之后渐显
时间: 2023-05-20 21:02:48 浏览: 100
你可以使用以下代码实现Unity中的渐隐和渐显效果:
//渐隐效果
IEnumerator FadeOut(GameObject obj, float time)
{
float elapsedTime = 0;
Color color = obj.GetComponent<Renderer>().material.color;
while (elapsedTime < time)
{
float alpha = Mathf.Lerp(color.a, 0, (elapsedTime / time));
color = new Color(color.r, color.g, color.b, alpha);
obj.GetComponent<Renderer>().material.color = color;
elapsedTime += Time.deltaTime;
yield return null;
}
}
//渐显效果
IEnumerator FadeIn(GameObject obj, float time)
{
float elapsedTime = 0;
Color color = obj.GetComponent<Renderer>().material.color;
while (elapsedTime < time)
{
float alpha = Mathf.Lerp(color.a, 1, (elapsedTime / time));
color = new Color(color.r, color.g, color.b, alpha);
obj.GetComponent<Renderer>().material.color = color;
elapsedTime += Time.deltaTime;
yield return null;
}
}
你可以在需要使用渐隐和渐显效果的地方调用这些协程。例如:
StartCoroutine(FadeOut(gameObject, 1f)); //渐隐
StartCoroutine(FadeIn(gameObject, 1f)); //渐显
希望这能帮助到你!
阅读全文