【发布时间】:2017-01-14 23:12:17
【问题描述】:
我正在创建一个脚本,允许对象在一段时间内褪色。
脚本运行良好,但是当对象淡出时,它在检查器和构建中仍然非常可见。
有人可以解释一下为什么以及如何使对象完全不可见吗? (我知道我可以“启用”该对象,但它使用的资源不是比褪色还多吗?我不知道 :()
如果我犯了任何错误,这里是代码(代码灵感来自统一论坛中的一个主题)
// Update is called once per frame
void Update ()
{
MyTime = Time.deltaTime;
AccumulatedTime += MyTime;
if (this.name == "Cube (1)")
{
Debug.Log(AccumulatedTime);
}
if (SwitchVisibility == 1)
{
if (AccumulatedTime >= Interval && AccumulatedTime<= 2*Interval || AccumulatedTime >= 3*Interval && AccumulatedTime<= 4*Interval)
{
StartCoroutine(FadeTo(0.0f, 1.0f));
SwitchVisibility = 0;
}
}
if (SwitchVisibility == 0)
{
if (AccumulatedTime >= 0 && AccumulatedTime <= Interval || AccumulatedTime >= 2*Interval && AccumulatedTime <= 3*Interval)
{
StartCoroutine(FadeTo(1.0f, 1.0f));
SwitchVisibility = 1;
}
}
if (AccumulatedTime >= Interval * 4.5f)
{
AccumulatedTime = 0;
}
}
IEnumerator FadeTo(float aValue, float aTime)
{
float alpha = MyRenderer.material.color.a;
for (float t = 0.0f; t < 1.0f; t += Time.deltaTime / aTime)
{
OriginalColor.a = Mathf.Lerp(alpha, aValue, t);
Color newColor = OriginalColor;
MyRenderer.material.color = newColor;
yield return null;
}
}
这是对象的样子:
【问题讨论】:
-
FadeTo函数中的aValue和aTime变量是什么?另外,你想随着时间的推移而褪色吗?您是否还想让对象在某个时候出现? -
aTime 是“for”语句中用于除以 Time.DeltaTime 的值。它设置淡化对象的速度。我每隔“间隔”秒淡化一次(在编辑器中设置间隔)。我可能没有正确解释问题,我的问题是我想让它完全不可见,代码运行良好(好吧,即使它不会使对象不可见)
-
为什么不输入
Debug.Log(alpha)并查看该值是否实际上为 0。这将有助于解决您的代码。告诉我结果。我知道了。不,您的代码无法正常工作。让我知道Debug.Log(alpha)的输出 -
Grmbl,我不知道为什么我没有考虑过......你是对的,alpha是0.006000......为什么不是0?
-
我猜这是因为浮点数和浮点数不精确。通常,将其设置为某个阈值的最小值/最大值是个好主意。类似
if alpha <= 0.01 -> alpha = 0。