- Home /
Fade In / Out not working C#
Hi!
What I want is that when I click de menu sprite the different menu option sprites display nicely with a fade in, or disappear in with a fade out. This is code, and it seems it works because the objects appear/disappear after 1 sec, but they do it directly, they don't fade in / out.
Please help me.
public class Options_script : MonoBehaviour {
public GameObject OptionsCanvas;
public GameObject Options1;
public GameObject Options2;
public GameObject Options3;
public GameObject Options4;
float downclick, upclick = 0f;
float delay = 0.8f;
bool ready = false;
// Use this for initialization
void Start ()
{
OptionsCanvas.SetActive(false);
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0) && ready == false)
{
Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero);
if (hit.collider != null)
{
if (hit.collider.name == "Options")
{
downclick = Time.time;
ready = true;
}
}
}
if (Input.GetMouseButtonUp(0) && ready == true)
{
Vector2 secondworldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D secondhit = Physics2D.Raycast(secondworldPoint, Vector2.zero);
if (secondhit.collider != null)
{
if (secondhit.collider.name == "Options")
{
upclick = Time.time;
ready = false;
}
}
}
if ((upclick - downclick) > delay)
{
OptionsCanvas.SetActive(true);
StartCoroutine(Fade(1f, 1f));
}
else
{
OptionsCanvas.SetActive(false);
StartCoroutine(Fade(0f, 1f));
}
}
IEnumerator Fade(float alphaValue, float alphaTime)
{
float alpha = Options1.transform.GetComponent<Renderer>().material.color.a;
for (float t = 0.0f; t < 1.0f; t += Time.deltaTime / alphaTime)
{
Color newColor = new Color(1, 1, 1, Mathf.Lerp(alpha, alphaValue, t));
Options1.transform.GetComponent<Renderer>().material.color = newColor;
yield return null;
}
}
}
Comment
Best Answer
Answer by Kishotta · Sep 22, 2017 at 08:11 PM
The issue is here:
yield return null;
This will have your coroutine loop through as quickly as it can (likely in less than the time of a single frame) and so it appears/disappears instantaneously.
Instead, you want to have your loop wait for the next frame before continuing.
yield return new WaitForEndOfFrame ();