1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Unityで事前にロードする方法。ロード後に数秒待つ実装。

Posted at

Unityで、前シーンにおいて事前にローディングすることで、よりスムーズにシーン遷移ができます。

ユーザー体験はノンストレスである必要があると思い、以下のようなスクリプトを実装しました。

ちなみに、以下では余計なアニメーション部分も実装されているので必要なければ Update() 中を省略して下さい。

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()
  {
    // シーンの読み込みを開始
    async = SceneManager.LoadSceneAsync("MainScene");
    // ロードが完了していても,シーンのアクティブ化は許可しない
    async.allowSceneActivation = false;
    
    while (async.progress<0.9f)
    {
      yield return null;
    }
    //ロード完了後。任意秒 待ってシーン遷移。
    yield return new WaitForSeconds(waitSec);
    async.allowSceneActivation = true;
  }

}

気をつけるべきは、AsyncOperation の性質で、非同期動作で使用するのですが、

上記スクリプト で while (!asny.isDone) とすると上手くいきませんでした。

async.isDoneは事前に

async.allowSceneActivation = false;

としてしまうと、常にfalseを返すようです。

また、この時

async.progressも最大でも0.9に留まることに注意して下さい。

追加情報があればコメントで是非。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?