在需要额外加载的场景上唤醒之前设置活动场景

时间:2019-06-17 16:25:54

标签: c# unity3d

我有一个加载器脚本,可以附加地加载场景。我遇到的问题是,在加载新场景时,它会检查它是否是Awake上的主要活动场景,如果不是,则使用此脚本加载该场景,然后该场景重新加载该场景。一个带有Awake检查的选项,从而创建了一个无限的场景加载循环。

使用此脚本,当我尝试设置主场景时,它表示尚未完成加载。如果我注释掉if语句,则会出现如上所述的场景加载循环。

那么,在加载场景的游戏对象组件上调用Awake之前,如何/如何设置活动场景?

注意:LoadScene()触发了UnityEvent

using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Events;
using System.Collections;

public class GSLoadComplete : MonoBehaviour {

  public LoadSceneMode mode;

  [Tooltip("Set the scene as the main scene (Only when mode is set to Addictive)")]
  public bool addictiveSetAsMain;

  public UnityEvent onAddictiveLoadCompleted;

  public void LoadScene(string sceneName) {
    if (mode == LoadSceneMode.Additive) {
      StartCoroutine(LoadSceneAddictive(sceneName));
    } else {
      SceneManager.LoadScene(sceneName, mode);
    }
  }

  IEnumerator LoadSceneAddictive(string sceneName) {

    AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(sceneName, mode);
    asyncLoad.allowSceneActivation = false;

    // Wait until the asynchronous scene fully loads
    while (!asyncLoad.isDone) {
      if (asyncLoad.progress >= 0.9f) {
        // Commenting this out creates an infinite load loop
        if (addictiveSetAsMain) {
          SceneManager.SetActiveScene(SceneManager.GetSceneByName(sceneName));
        }
        asyncLoad.allowSceneActivation = true;
      }
      yield return null;
    }

    onAddictiveLoadCompleted.Invoke();
  }

}

这是在Awake上加载的脚本:

using UnityEngine;
using UnityEngine.SceneManagement;

public class LoadMain : MonoBehaviour {

  public string scene;

  void Awake() {
    if (SceneManager.GetActiveScene().name != scene) {
      SceneManager.LoadScene(scene, LoadSceneMode.Single);
    }
  }

}

0 个答案:

没有答案