我有几个精灵,我想在游戏的演职员表场景中循环使用淡入/淡出效果。我有一个可以工作的脚本,但它只适用于一个精灵。如何制作它,以便我可以有一个可以循环浏览的精灵列表?
using UnityEngine;
using System.Collections;
public class possible : MonoBehaviour
{
public SpriteRenderer sprite;
public Color spriteColor = Color.white;
public float fadeInTime = 1.5f;
public float fadeOutTime = 3f;
public float delayToFadeOut = 5f;
public float delayToFadeIn = 5f;
void Start()
{
StartCoroutine("FadeCycle");
}
IEnumerator FadeCycle()
{
float fade = 0f;
float startTime;
while (true)
{
startTime = Time.time;
while (fade < 1f)
{
fade = Mathf.Lerp(0f, 1f, (Time.time - startTime) /
fadeInTime);
spriteColor.a = fade;
sprite.color = spriteColor;
yield return null;
}
//Make sure it's set to exactly 1f
fade = 1f;
spriteColor.a = fade;
sprite.color = spriteColor;
yield return new WaitForSeconds(delayToFadeOut);
startTime = Time.time;
while (fade > 0f)
{
fade = Mathf.Lerp(1f, 0f, (Time.time - startTime) /
fadeOutTime);
spriteColor.a = fade;
sprite.color = spriteColor;
yield return null;
}
fade = 0f;
spriteColor.a = fade;
sprite.color = spriteColor;
yield return new WaitForSeconds(delayToFadeIn);
}
}
}
首先,让我们做一个简单的重构,并获取执行实际工作的位,并将其分离成一个方法。所以那两行:
spriteColor.a = fade;
sprite.color = spriteColor;
可以变成一个方法,并在 youro 代码中调用
void SetFade(float fade)
{
spriteColor.a = fade;
sprite.color = spriteColor;
}
然后,代码的其余部分会变短,并且已经可读
:IEnumerator FadeCycle()
{
float startTime;
while (true)
{
startTime = Time.time;
while (fade < 1f)
{
fade = Mathf.Lerp(0f, 1f, (Time.time - startTime) / fadeInTime);
SetFade(fade);
yield return null;
}
SetFade(1);
yield return new WaitForSeconds(delayToFadeOut);
startTime = Time.time;
while (fade > 0f)
{
SetFade(Mathf.Lerp(1f, 0f, (Time.time - startTime) / fadeOutTime));
yield return null;
}
SetFade(0);
yield return new WaitForSeconds(delayToFadeIn);
}
}
}
现在,如果你想将更改应用于多个精灵,你只需要在一个地方做 int。将您的声明从:
public SpriteRenderer sprite;
自
public SpriteRenderer[] sprites;
最后,我们可以将 SetFade 方法修改为:
void SetFade(float fade)
{
spriteColor.a = fade;
foreach(var sprite in sprites)
sprite.color = spriteColor;
}
我不确定您要做什么,但很快您可以添加一个黑色精灵/画布图像,该图像覆盖 alpha = 0 的所有场景,并使用您的类似方法将 alpha 更改为 1。它应该比循环每个精灵具有更好的性能。
如果你想单独控制每个精灵:将 SpriteRenderer 参数添加到你的方法中,并将你的所有精灵存储在一个列表中,然后在 spriteList 中为每个精灵调用你的方法。为了更好地练习,你可以向SpriteRenderer添加一个扩展方法