Unity 2D Sprite Fade In/Out OnTriggerEnter2D
Hello!
First I'd like to establish I'm very VERY new to coding. This being said, I'm currently messing around with the 2D engine, and what I want to happen is have the player enter a trigger volume and when they do a sprite fades to a completely transparent alpha, and then when they exit the trigger volume it goes back to a 100% alpha.
I've found some codes that I was able to somewhat modify to the task, however in one way or another they don't exactly meet what I want. I've been trying to modify a particular code to no avail, however in its untouched state it does exactly what I want except on a clock instead of when they player enters/exits a trigger.
When I change it to OnTriggerEnter2D instead of start function, it triggers the clock. Then I tried making a boolean variable that would make it so the coroutine would run only once, however that didn't work and it looped no matter what I tried. Then I tried getting rid of the coroutine and just making the OnTriggerEnter function run the code, however because it's using yield return I have to have it in an IEnumerator which I'm not sure how to trigger with a function. I've also tried looking into using the actual SpriteRenderer component, however from my research searching through UnityAnswers they said it's apparently unstable to change it with that.
What would you recommend I do? Here's the original code I've been trying to modify, courtesy of another Unity Answers post.
using UnityEngine;
using System.Collections;
public class Fade : MonoBehaviour
{
public SpriteRenderer sprite;
public Color spriteColor = Color.white;
public float fadeInTime = 1.5f;
public float fadeOutTime = 3f;
public float delayToFadeOut = 5f;
public float delayToFadeIn = 5f;
void Start()
{
StartCoroutine("FadeCycle");
}
IEnumerator FadeCycle()
{
float fade = 0f;
float startTime;
while(true)
{
startTime = Time.time;
while(fade < 1f)
{
fade = Mathf.Lerp(0f, 1f, (Time.time - startTime) / fadeInTime);
spriteColor.a = fade;
sprite.color = spriteColor;
yield return null;
print ("Step 1");
}
//Make sure it's set to exactly 1f
fade = 1f;
spriteColor.a = fade;
sprite.color = spriteColor;
yield return new WaitForSeconds(delayToFadeOut);
print ("Step 2");
startTime = Time.time;
while(fade > 0f)
{
fade = Mathf.Lerp(1f, 0f, (Time.time - startTime) / fadeOutTime);
spriteColor.a = fade;
sprite.color = spriteColor;
yield return null;
print ("Step 3");
}
fade = 0f;
spriteColor.a = fade;
sprite.color = spriteColor;
yield return new WaitForSeconds(delayToFadeIn);
print ("Step 4");
}
}
}