Fade in/out from LoadScene to Unity

Asked 2 years ago, Updated 2 years ago, 70 views

My project is to make VR mobile app Unity.

The problem is I want to include the fade in/out effect in LoadScene, but it's different for each online course, and most of them are 2D screens, so I'm having a hard time implementing them because they're different from what I do. See LoadScene OnClick.

At the beginning, we added the fade in and out effects, but we don't move on to the next scene. I want to be familiar with the time control of Fade in/out and the part that moves on to the next scene and use it well in the future. Help!


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

public class LoadSceneOnClick : MonoBehaviour
{
    public int index;
    public string levelName;

    public GUITexture black;
    public Animator anim;

    public void LoadByIndex(int sceneIndex)
    {
        StartCoroutine(Fading());

    }
    IEnumerator Fading()
    {
        anim.SetBool("Fade", true);
        yield return new WaitUntil(() => black.color.a == 1);
        SceneManager.LoadScene("1_EarthMenu");
    }


}

fade loadscene unity c#

2022-09-21 19:44

2 Answers

I think the a value of color is caused by float. It is not recommended to use == operation on float. Even if they both have values of 1, they may not be the same.

Running the code below, b increases from 0.9 to 0.01 and increases to 1.1. If you run the code (press the Run button under the code), b must have a single moment, but b==1 will not be printed.

using System;

public class Hello1 {
    public static void Main() {
        float b = 0.9f;
        System.Console.WriteLine("b: "+b);
        for(int i=0;i<20;i++){
            if(b==1){
                System.Console.WriteLine("b==1");
            }
            if(Math.Abs(1-b)<0.001f){
                System.Console.WriteLine ("b is almost 1");
            }            
            b+=0.01f;
        }
        System.Console.WriteLine("b: "+b);  
    }
}

This is a problem that arises from floating points, a way of representing real numbers as binary numbers. For more information, see here .

Even if you don't understand the details, I hope you know that the comparison of float (double) is the same as the range (e.g., less than 0.001) rather than using the == operation.

To apply it, write using System; at the top of the code black.color.a == 1 Math.Try switching to Abs(black.color.a - 1)<0.001f.


2022-09-21 19:44

Thank you for the example description. To be honest, it's hard to understand what you explained because of the lack of basics.

Could you tell me how to apply it in my script?


2022-09-21 19:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.