DEV Community

Cover image for How to preloading on Unity. My script waiting few seconds after loading.
Kaede Games 🎮
Kaede Games 🎮

Posted on

How to preloading on Unity. My script waiting few seconds after loading.

Preloading is one of the best ways which reduce user’s stress easily.

So, I created the loading.cs for preloading.

If you don’t need animation system, please get rid of below part,

Update(){——-}

Script

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

public class Loading : MonoBehaviour
{


  private AsyncOperation async;
  public Text loadingText;
  public float waitSec = 5.0f;
  public float cycle=0.8f;
  float time=0;
  void Start()
  {
    StartCoroutine("LoadData");
  }

    private void Update()
    {
    time += Time.deltaTime;

        if(time <= (cycle/5f))
      loadingText.text = "Now loading";
    else if (time <= (cycle * 2 / 5f))
      loadingText.text = "Now loading.";
    else if (time <= (cycle * 3 / 5f))
      loadingText.text = "Now loading..";
    else if (time <= (cycle * 4 / 5f))
      loadingText.text = "Now loading...";
    else if (time <= cycle)
        {
      time = 0;
        }


  }
    IEnumerator LoadData()
  {
    // Start loading scene
    async = SceneManager.LoadSceneAsync("MainScene");

    // Dont activate changing scene when the load finished.
    async.allowSceneActivation = false;

    while (async.progress<0.9f)
    {
      yield return null;
    }
    //change scene after wait some seconds
    yield return new WaitForSeconds(waitSec);
    async.allowSceneActivation = true;
  }

}
Enter fullscreen mode Exit fullscreen mode

Postscript

BTW, be careful about “AsyncOperation”

In this script, preloading work
while (async.progress<0.9f)

but didn't work
while (!asny.isDone)

It's because when you define async.allowSceneActivation = false;
at first,

async.isDone always return false

and

async.progress couldn’t reach 1.0 but 0.9

the max state will be 0.9.

Best regards.

I write this post to improve my English skill. Don’t mind some spelling mistake.

Top comments (0)