hyun luse
hyun luse

Reputation: 21

using fade out effect to load scene in Unity, but it doesn't work at all

Now I'm making C# script to load scene after fade out effect.
First scene has a panel and the tag of the panel is image.
The name of the second scene is EndingCredit.

But when I added this script to panel(panel is below the canvas) and clicked play button, it didn't work at all.

The code is below.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

/*
 * script explanation
 * shows Earth image and fade out  
 * after fade out effect, load EndingCredit Scene 
 */

public class LoadToCredit : MonoBehaviour
{
    public Image image;

    // Start is called before the first frame update
    void Start()
    {
        //SceneManager.LoadScene("EndingCredit");
        FadeEffect();
    }

    private IEnumerator FadeEffect()
    {
        float fadeCount = 0; //initial alpha value

        while (fadeCount < 1.0f)
        {
            fadeCount += 0.01f; //lower alpha value 0.01 per 0.01 second 
            yield return new WaitForSeconds(0.01f); //per 0.01 second
            image.color = new Color(0, 0, 0, fadeCount); //makes image look transparent  
        }
        //after while loop ends, load EndingCredit scene
        SceneManager.LoadScene("EndingCredit");
    }

    // Update is called once per frame
    void Update()
    {
        //FadeEffect();
        //SceneManager.LoadScene("EndingCredit");
    }
}

I tested another code that using LoadScene().
And this script worked properly.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

/*
 * script explanation
 * shows Earth image and fade out  
 * after fade out effect, load EndingCredit Scene 
 */

public class LoadToCredit : MonoBehaviour
{
    public Image image;

    // Start is called before the first frame update
    void Start()
    {
       
    }

    // Update is called once per frame
    void Update()
    {
        SceneManager.LoadScene("EndingCredit");
    }
}

Here's some questions.

  1. If the script is to fix, how should I fix it properly?
  2. Is it okay to locate SceneManager.LoadScene("EndingCredit"); in FadeEffect?
  3. What I want is that after the panel of the first Scene fades out, than after 2 seconds EndingCredit comes.

Thank you for reading this question.

Upvotes: 2

Views: 745

Answers (1)

KiynL
KiynL

Reputation: 4266

Call FadeEffect as coroutine:

void Start() => StartCoroutine(FadeEffect());

Upvotes: 1

Related Questions