Hello, I’ve got this code:
private void Update() {
if (Input.GetKeyDown("f")) {
StartCoroutine(Fade());
}
if (performFade) {
StartCoroutine(Fade());
}
}
IEnumerator Fade() {
Color c = _spriteRenderer.material.color;
for (float alpha = 1f; alpha >= -0.2; alpha -= 0.1f) {
c.a = alpha;
_spriteRenderer.material.color = c;
yield return new WaitForSeconds(.1f);
}
performFade = false;
}
private void OnTriggerEnter2D(Collider2D other) {
if (other.CompareTag("Player")) {
performFade = true;
}
}
This works fine when uses by pressing the f
key.
But when invoked from within OnTriggerEnter2D
I get flickering on the fading.
The Coroutine example is taken directly from the Unity manual so I think it’s pretty solid
I’ve seen multiple posts on how to achieve this effect on trigger but none of them work properly (including the one by the chap who says never to use Coroutines for this but doesn’t explain why not). Sorry, I can’t find the links now.
My understanding is that because this is a Coroutine, it would execute the fading one frame at a time. And, as I say, it works fine when triggered by the keyboard press but not with OnTriggerEnter2D
. Any ideas why that might be?
Does OnTriggerEnter
do some other sort of magic that I’m unaware of?
Any help would be greatly appreciated.
Thanks