- Home /
Weird behaviour when coroutine fader is called in the middle of a fade
I'm trying to create a location indicator that fades in/out when you click/arrive at destination. However, if I click a new location just as the location indicator has begun fading, the new location indicator will have the opacity/state of the prior indicator.... if that makes sense?
If I'm really unlucky, it's possible to click a new location just as the indicator has 0 alpha value, making the newly placed indicator invisible.
Is it possible to prevent this behaviour?
Here is the script that controls the fading:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class TargetIndicatorFade : MonoBehaviour
{
[Range(0.01f, 15f)]
public float fadeSpeed = 5.5f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//Fade in target indicator on mouse click, then
if (Input.GetMouseButtonDown(0))
{
StartCoroutine(FadeInObject());
}
}
//fade out target indicator on player arrival
private void OnTriggerEnter(Collider other)
{
StartCoroutine(FadeOutObject());
}
public IEnumerator FadeOutObject()
{
while (this.GetComponent<Renderer>().material.color.a > 0)
{
Color objectColor = this.GetComponent<Renderer>().material.color;
float fadeAmount = objectColor.a - (fadeSpeed * Time.deltaTime);
objectColor = new Color(objectColor.r, objectColor.g, objectColor.b, fadeAmount);
this.GetComponent<Renderer>().material.color = objectColor;
yield return null;
}
}
public IEnumerator FadeInObject()
{
while (this.GetComponent<Renderer>().material.color.a < 1)
{
Color objectColor = this.GetComponent<Renderer>().material.color;
float fadeAmount = objectColor.a + (fadeSpeed * Time.deltaTime);
objectColor = new Color(objectColor.r, objectColor.g, objectColor.b, fadeAmount);
this.GetComponent<Renderer>().material.color = objectColor;
yield return null;
}
}
}
Comment
Your answer
Follow this Question
Related Questions
Fade In / Out not working C# 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How can I fade in/out an object nonstop automatic ? 2 Answers