c# - 如何停止协程但让 alpha 颜色在停止前先完成褪色?
问题描述
我有两个问题:
我不得不使用旗帜和休息时间;停止 Coroutine CanvasAlphaChangeOverTime 只是做:
StopCoroutine("CanvasAlphaChangeOverTime"); 没有阻止它。
如果褪色在去往 0 或去往 1 的路上移动到 0 并且我停止 Coroutine CanvasAlphaChangeOverTime 首先它将完成褪色到 0 或 1 的方向然后停止协程?
现在,当协程停止时,它会在中间停止褪色,我希望褪色首先完成然后停止。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FadeInOutSaveGameText : MonoBehaviour
{
public Animator animator;
public Canvas canvas;
public float fadingSpeed;
private bool stopFading = false;
// Start is called before the first frame update
void Start()
{
StartCoroutine(OverAllTime(5f));
}
IEnumerator CanvasAlphaChangeOverTime(Canvas canvas, float duration)
{
var alphaColor = canvas.GetComponent<CanvasGroup>().alpha;
while (true)
{
alphaColor = (Mathf.Sin(Time.time * duration) + 1.0f) / 2.0f;
canvas.GetComponent<CanvasGroup>().alpha = alphaColor;
if (stopFading == true)
{
break;
}
yield return null;
}
}
IEnumerator OverAllTime(float time)
{
StartCoroutine(CanvasAlphaChangeOverTime(canvas, fadingSpeed));
yield return new WaitForSeconds(time);
stopFading = true;
StopCoroutine("CanvasAlphaChangeOverTime");
}
}
解决方案
如果你想停止你的协程,你必须将 StartCoroutine(...) 的返回值存储在一个成员变量中,并通过它的引用显式地停止它:
private Coroutine coroutine;
[...]
private void StartRoutine
{
if(coroutine == null)
coroutine = StartCoroutine(...);
}
private void StopRoutine
{
if(coroutine != null)
{
StopCoroutine(coroutine);
coroutine = null;
}
}
但是在您的情况下,您不想停止协程,因为您希望它继续直到达到它的转折点(然后自行完成)。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FadeInOutSaveGameText : MonoBehaviour
{
private const float THRESHOLD = 0.01F;
[...]
IEnumerator CanvasAlphaChangeOverTime(Canvas canvas, float duration)
{
var alphaColor = canvas.GetComponent<CanvasGroup>().alpha;
while (true)
{
alphaColor = (Mathf.Sin(Time.time * duration) + 1.0f) / 2.0f;
canvas.GetComponent<CanvasGroup>().alpha = alphaColor;
// only break, if current alpha value is close to 0
if (stopFading && Mathf.Abs(alphaColor) <= THRESHOLD)
{
break;
}
yield return null;
}
}
IEnumerator OverAllTime(float time)
{
StartCoroutine(CanvasAlphaChangeOverTime(canvas, fadingSpeed));
yield return new WaitForSeconds(time);
stopFading = true;
// do not stop routine, since it should run on until reaching 0
//StopCoroutine("CanvasAlphaChangeOverTime");
}
}
推荐阅读
- sql - Need help for Oracle SQL query
- reactjs - 如何在 react-native 中将动态道具传递给类?
- javascript - 如何解决“无法在 'Window' 上执行 'postMessage':需要 2 个参数,但只有 1 个存在。”
- r - 如何将函数应用于每个元素包含不同大小的列表的矩阵
- php - PHP - 共享主机环境中长时间运行的进程
- javascript - 如何在多个 HTML 文件上运行函数并将所有执行的输出写入单个文件
- javascript - 在 Chrome 上使用 Javascript 获取打印页面宽度/高度
- python - 为什么这个并行化的脚本没有返回正确的结果?
- swift - 我应该在 UIViewController 生命周期的哪个时刻初始化属性?
- php - 使用 Kreait 的 Firebase 推送通知