Where possible, we should avoid adding code to the Update() method since this is invoked every frame, which means it can reduce the performance of our games, especially if many objects have scripted components with Update() methods, all testing flags every frame.
One very effective solution is to invoke a coroutine when we want some actions to be performed over several frames. This is because a coroutine can perform some actions, then yield control back to the rest of the scene, and then resume its actions from where it left off, and so on until its logic is completed.
Do the following:
- Remove the Update() method.
- Add a new using statement at the top of the script class since coroutines return an IEnumerator value, which is part of the System.Collections package:
using System.Collections;
- Add a new method:
private IEnumerator FadeFunction() {
while (isFading)
...