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に留まることに注意して下さい。
追加情報があればコメントで是非。