所以,我有一些文本在没有手榴弹的情况下显示,目前,它在2秒钟后消失,然后永远闪烁。我只想让它出现2秒钟然后消失。非常感谢您的帮助!
if (amountOfGrenades == 0)
{
StartCoroutine(ShowandHideGrenadeText(NOgrenadesText));
}
IEnumerator ShowandHideGrenadeText(GameObject NOgrenadesText)
{
NOgrenadesText.SetActive(true); // Enable the text so it shows
yield return new WaitForSeconds(2.0f);
NOgrenadesText.SetActive(false); // Disable the text so it is hidden
yield return new WaitForSeconds(2.0f);
}
由于没有提供太多上下文,我猜:您正在启动数百个并行协程,因为在满足条件的情况下,您的第一个代码段在每个帧的Update中被调用。。。
只需添加第二个条件,例如
if (amountOfGrenades == 0 && !NOgrenadesText.activeSelf)
{
StartCoroutine(ShowObjectForTwoSeconds(NOgrenadesText));
}
// In general be careful with paramter names and existing fields with the same name
// you might confuse them at some point
IEnumerator ShowObjectForTwoSeconds(GameObject obj)
{
obj.SetActive(true); // Enable the text so it shows
yield return new WaitForSeconds(2.0f);
obj.SetActive(false); // Disable the text so it is hidden
}
注意,在一个Coroutine末尾的yield
没有什么意义;(
或者,如果您真的想在重新关闭后等待2秒才能再次打开它,那么只需引入一个额外的标志,例如
if (amountOfGrenades == 0 && ! alreadyShowing
{
StartCoroutine(ShowObjectForTwoSeconds(NOgrenadesText));
}
private bool alreadyShowing;
// In general be careful with paramter names and existing fields with the same name
// you might confuse them at some point
IEnumerator ShowObjectForTwoSeconds(GameObject obj)
{
alreadyShowing = true;
obj.SetActive(true); // Enable the text so it shows
yield return new WaitForSeconds(2.0f);
obj.SetActive(false); // Disable the text so it is hidden
yield return new WaitForSeconds(2.0f);
alreadyShowing = false;
}
只是给您另一种处理这种情况的可能性:
你有没有想过用动画来处理这类事情?我所说的动画是指";不是一起出游">
有多种方法可以设置动画。您可以使用AnimationCurve
并根据所述曲线设置文本的颜色。或者,您可以创建一个动画,并为UI的该部分指定一个动画师。在代码中,您只需触发动画师的状态更改。
推论可以用于你想要的效果,但它们也会带来问题。
这可能不是你问题的直接答案,而是你目前可能遇到的xy问题的解决方案。