- 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
- Coroutines must have a return value of
- Make
FadeOut()
yield return to nullyield 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 awhile
statement forelapsed < duration
- In the
while
loop, incremenetelapsed
byTime.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
fromInteract()
and delete_isFading
- Add a call to
StartCoroutine(FadeOut)
toInteract()
- Now we can simply start our coroutine when the interaction occurs
Last active
October 4, 2021 20:26
-
-
Save charlieamat/4b7d4f6962315813a54e55d688449a03 to your computer and use it in GitHub Desktop.
[ta-edu-course-survival-game] Chapter 2 — Coroutines (2)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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