using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Fader : MonoBehaviour
{
#region FIELDS
public GameObject fadeOutUIGameobjectImage;
public float fadeSpeed = 0.8f;
public bool fadeOnStart = false;
private Image fadeOutUIImage;
private void Start()
{
if(fadeOnStart == true)
{
StartCoroutine(Fade(FadeDirection.Out));
}
}
public enum FadeDirection
{
In, //Alpha = 1
Out // Alpha = 0
}
#endregion
#region FADE
public IEnumerator Fade(FadeDirection fadeDirection)
{
fadeOutUIGameobjectImage.SetActive(true);
float alpha = (fadeDirection == FadeDirection.Out) ? 1 : 0;
float fadeEndValue = (fadeDirection == FadeDirection.Out) ? 0 : 1;
if (fadeDirection == FadeDirection.Out)
{
while (alpha >= fadeEndValue)
{
SetColorImage(ref alpha, fadeDirection);
yield return null;
}
fadeOutUIGameobjectImage.SetActive(false);
}
else
{
fadeOutUIGameobjectImage.SetActive(true);
while (alpha <= fadeEndValue)
{
SetColorImage(ref alpha, fadeDirection);
yield return null;
}
}
}
#endregion
#region HELPERS
public IEnumerator FadeAndLoadScene(FadeDirection fadeDirection, string sceneToLoad)
{
yield return Fade(fadeDirection);
SceneManager.LoadScene(sceneToLoad);
}
private void SetColorImage(ref float alpha, FadeDirection fadeDirection)
{
if (fadeOutUIImage == null)
{
fadeOutUIImage = fadeOutUIGameobjectImage.GetComponent<Image>();
}
fadeOutUIImage.color = new Color(fadeOutUIImage.color.r, fadeOutUIImage.color.g, fadeOutUIImage.color.b, alpha);
alpha += Time.deltaTime * (1.0f / fadeSpeed) * ((fadeDirection == FadeDirection.Out) ? -1 : 1);
}
#endregion
}
In this case it's Image but if for example the variable fadeOutUIGameobjectImage is a Text or CanvasRenderer or only Canvas or a Cube or Cylinder or any ui element then in the two lines :
private Image fadeOutUIImage;
And
fadeOutUIImage = fadeOutUIGameobjectImage.GetComponent<Image>();
It's related to Image type, Is there a way to find the type automatic ? Sometimes I might want to fade a Cube or a Canvas or a CanvasRenderer or Text or TextMesh or TextMeshPro or Image or MeshRenderer or maybe making an array of fadeOutUIGameobjectImage instead a single one like now.
The idea is to detect the type automatic.