如果是同步加载场景,也就是SceneManager.LoadScene(),避免在场景加载完成前加载资源,下面是一个错误示例:
void DoSomething(){
SceneManager.LoadScene(paperType.SceneName);
Resources.Load<GameObject>(prefabPath);
}
上面的虽然是同步加载场景,但是在LoadScene执行完成下一步处理资源时,当前场景依然是上一个场景,下面是一种正确的加载方式
public void DoSomething(){
SceneManager.sceneLoaded += loadScene;
SceneManager.LoadScene(paperType.SceneName);
}
private void loadScene(Scene s, LoadSceneMode l)
{
Resources.Load<GameObject>(prefabPath);
SceneManager.sceneLoaded -= loadScene;
}
下面是异步资源加载
public void DoSomething(){
var loadSceneOperation = SceneManager.LoadSceneAsync(sceneName);
StartCoroutine(nameof(ILoadScene),loadSceneOperation);
}
protected IEnumerator ILoadScene(AsyncOperation asyncOperation)
{
while (!asyncOperation.isDone)
{
yield return null;
}
Resources.Load<GameObject>(prefabPath);
}