I think you should rather make your field
private Coroutine currentFlashCoroutine;
and then use
currentcurrentFlashCoroutine = StartCoroutine(ChangeColor(material, colOrig, Color.white);
and then do
if(currentFlashCoroutine != null)
{
StopCoroutine (currentFlashCoroutine);
currentFlashCoroutine = null;
}
Btw in doubt you could also use StopAllCoroutines
since in your use case you seem to anyway only have a single routine in your class ;)
The second issue here is that you are stopping and starting a new routine every frame as long the condition is true.
You would rather do somthing like
void Update()
{
// this bool and int change when the line and rect are interacted with
if (rect.isIntermediate || rect.activeDirection != 0)
{
// only start a new routine if there is not already one running
if(currentFlashCoroutine == null)
{
currentFlashCoroutine = StartCoroutine(ChangeColor(material, colOrig, Color.white);
}
}
else
{
if(currentFlashCoroutine != null)
{
StopCoroutine (currentFlashCoroutine);
currentFlashCoroutine = null;
}
}
}
IEnumerator ChangeColor(Material toChange, Color32 startColor, Color32 endColor)
{
var t = 0f;
var colorDuration = Random.Range(2.49f, 6f);
while (t < colorDuration)
{
var timeDuration = Random.Range(.55f, .95f);
if (t > timeDuration)
{
t = 0;
}
t += Time.deltaTime;
toChange.color = Color.Lerp(startColor, endColor, t / colorDuration);
yield return null;
}
currentFlashRoutine = null;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…