In the Hierarchy I have a Canvas set to Screen Space - Overlay the canvas name is Scene Fader. and a child disabled ui Image and also a child name Scene Fader Child that is a gameobject with a script attached to it name Scene Fader :
The script that attached to Scene Fader Child is :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class SceneFader : MonoBehaviour
{
#region FIELDS
public GameObject fadeOutUIGameobjectImage;
public float fadeSpeed = 0.8f;
//public SaveLoad saveLoad;
private Image fadeOutUIImage;
private void Start()
{
SceneManager.sceneLoaded += SceneManager_sceneLoaded;
}
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 SceneManager_sceneLoaded(Scene arg0, LoadSceneMode arg1)
{
if (MenuController.LoadSceneForSavedGame == true)
{
var saveLoad = GameObject.Find("Save System").GetComponent<SaveLoad>();
saveLoad.Load(null, null);
}
if(MouseHover.loadingwithfolder)
{
var saveLoad = GameObject.Find("Save System").GetComponent<SaveLoad>();
saveLoad.Load(MouseHover.folder, MouseHover.savedGameFName);
MouseHover.loadingwithfolder = false;
}
}
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
}
When in this script I'm enabling true the fadeOutUIGameobjectImage I want that this Image will become in front of anything else all the ui elements and other stuff.
Now there is some ui elements that are in front of it.
This screenshot show the default main menu when running the game :
Then when starting a new game everything is fade out the screen get black using the Scene Fader script but the left ui element is in front of the image in the scene fader script :