unity写一个异步加载场景的万能脚本
时间: 2024-03-11 14:48:42 浏览: 175
好的,以下是一个异步加载场景的万能脚本:
```csharp
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
public class SceneLoader : MonoBehaviour
{
public string sceneName; // 要加载的场景名
public bool asyncLoad; // 是否异步加载
private void Start()
{
if (asyncLoad)
{
StartCoroutine(LoadSceneAsync(sceneName));
}
else
{
SceneManager.LoadScene(sceneName);
}
}
IEnumerator LoadSceneAsync(string sceneName)
{
yield return null;
AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(sceneName);
asyncOperation.allowSceneActivation = false;
while (!asyncOperation.isDone)
{
float progress = Mathf.Clamp01(asyncOperation.progress / 0.9f);
Debug.Log("Loading progress: " + (progress * 100) + "%");
if (progress >= 0.9f)
{
asyncOperation.allowSceneActivation = true;
}
yield return null;
}
}
}
```
通过设置 `sceneName` 和 `asyncLoad` 属性,可以控制该脚本的行为。如果 `asyncLoad` 为 true,那么场景将会异步加载;否则,将会同步加载。如果是异步加载,那么 `LoadSceneAsync()` 函数会被调用,该函数会启动一个协程来进行异步加载,并且会在加载完成后自动切换到新场景。在异步加载的过程中,可以通过 `asyncOperation.progress` 属性来获取加载进度,并且在加载完成后调用 `asyncOperation.allowSceneActivation = true` 来切换到新场景。
阅读全文