MissingReferenceException: The object of type ‘SceneFader’ has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
this script is attached to gameobject that i made from it a prefab.
i use the prefab in the main menu scene the default starting loaded scene.
the fading is working fine when starting a new game. fading out then fading in back when the new scene has loaded.
the fade in line 67 is working fine:
yield return Fade(fadeDirection);
but then after the game scene has loaded and it should fade in back at line 73 i get the error:
StartCoroutine(Fade(FadeDirection.Out));
the full script:
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class SceneFader : MonoBehaviour
{
#region FIELDS
public GameObject fadeOutUIGameobjectImage;
public float fadeSpeed = 3f;
public bool fadeEnded = false;
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;
}
fadeEnded = true;
}
}
#endregion
#region HELPERS
public IEnumerator FadeAndLoadScene(FadeDirection fadeDirection, string sceneToLoad)
{
yield return Fade(fadeDirection);
SceneManager.LoadSceneAsync(sceneToLoad);
}
private void SceneManager_sceneLoaded(Scene arg0, LoadSceneMode arg1)
{
MenuController.newGameClicked = false;
StartCoroutine(Fade(FadeDirection.Out));
if (MenuController.LoadSceneForSavedGame == true)
{
}
}
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
}
this screenshot shows the two scenes. and the prefab Scene Fader is in both scenes.
then when running the game (OfCourse only the main menu scene is in the hierarchy at start) and starting a new game it’s loading the Awakening scene, and the Scene Fader does exist. but still, it throws the error exception.
if the scene Awakening has loaded and the Scene Fader does exist, why does it show the exception error?