Skip to content

Instantly share code, notes, and snippets.

@charlieamat
Last active October 4, 2021 20:26
Show Gist options
  • Save charlieamat/4b7d4f6962315813a54e55d688449a03 to your computer and use it in GitHub Desktop.
Save charlieamat/4b7d4f6962315813a54e55d688449a03 to your computer and use it in GitHub Desktop.
[ta-edu-course-survival-game] Chapter 2 — Coroutines (2)
  • Implement IEnumerator FadeOut()
    • Coroutines must have a return value of IEnumerator
    • This is because they're based on iterator methods
    • You can use iterator methods to create a source for enumeration
    • Every value that you yield return from an iterator method is essentially a part of a collection that the method represents
    • Unity treats the collection that coroutines return as instructions for when to continue exectution, if ever
  • Make FadeOut() yield return to null
    • yield return null instructs to skip one frame before contining execution
    • In this case, there's nothing else to execute so nothing else will happen
  • Declare a local variable named "elapsed" with a value of 0
    • FadeOut() will be responsible for the fade state now
  • Wrap yield return null with a while statement for elapsed < duration
  • In the while loop, incremenet elapsed by Time.deltaTime
    • Now this function will continue to execute once every frame until elapsed is greater than duration
  • Copy the fading logic (lines 26-28) and paste it into FadeOut()
  • Delete Update() and _elapsed
    • We no longer need to keep track of state or manage the fade using update
  • Remove call to _isFading from Interact() and delete _isFading
  • Add a call to StartCoroutine(FadeOut) to Interact()
    • Now we can simply start our coroutine when the interaction occurs
public class FadingInteractable : Interactable
{
[SerializeField] private float duration = 3;
private Renderer _renderer;
public void Interact()
{
StartCoroutine(FadeOut);
}
private void Awake()
{
if (!TryGetComponent(out Renderer renderer))
{
this.enabled = false;
return;
}
}
private IEnumerator FadeOut()
{
var elapsed = 0;
while (elapsed <= duraion)
{
var color = _renderer.material.color;
color.a = Mathf.Lerp(1, 0, elapsed / duration);
_renderer.material.color = color;
elapsed += Time.deltaTime;
yield return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment