c# - UnityException : GetActiveScene is not allowed to be called from a MonoBehaviour constructor

标签 c# unity3d compiler-errors 3d scene-manager

我正在尝试创建一个保存级别系统,并且继续出现此错误。

UnityException: GetActiveScene is not allowed to be called from a MonoBehaviour constructor


我尝试过搜索,但是没有结果。这是我使用的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class EndLevel : MonoBehaviour
{
    public PlayerMovement pm;

    public GameObject completeLevelUI;

    // Start is called before the first frame update
    void Start() { 
    }

    // Update is called once per frame
    void Update() {
    }

    void OnCollisionEnter (Collision collisionInfo) {
        if(collisionInfo.collider.tag == "Finish") {
            Debug.Log("You beat the level!");
            pm.enabled = false;
            completeLevelUI.SetActive(true);
            Level = Level + 1;
            PlayerPrefs.SetFloat("Level", Level);
            Debug.Log("Saved");
            Invoke("NextLevel", 3);
        }
    }

    public void NextLevel() {
        SceneManager.LoadScene (SceneManager
            .GetActiveScene().buildIndex + 1);
    }
}
对错误有任何想法吗?

最佳答案

您必须使用 Start() Awake() 方法获取当前 Activity 的场景。
Start() 的示例:

private int sceneNumber;

private void Start() {
    sceneNumber = SceneManager.GetActiveScene().buildIndex;
}
作为替代解决方案,您也可以使用Lazzy Getter。这意味着在场景加载和使用之间,该值不会过时,这可能与其他数据有关。
Lazzy Getter的示例:
private int sceneNumber { 
    get { 
        return SceneManager.GetActiveScene().buildIndex; 
    }
}

使用这些解决方案中的任何一个时,现在都可以在 scenenumber + 1 函数调用中简单地调用SceneManager.Load()
另外,您需要确保正在调用 IEnumerator ,而不是调用Function调用。如果要延迟场景加载。
函数调用:
private void OnCollisionEnter (Collision collisionInfo) {
    ...
    StartCoroutine(NextLevel(3f));
    ...
}

private IEnumerator NextLevel(float seconds) {
    yield return new WaitForSeconds(seconds);
    SceneManager.LoadScene(sceneNumber + 1);
}

关于c# - UnityException : GetActiveScene is not allowed to be called from a MonoBehaviour constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64982077/

相关文章:

c# - 为什么添加 List<T> 也会添加到不同的 List<T>?

objective-c - CGRectIntersection是否需要标量类型?

compiler-errors - 每10分钟发送一次电子邮件通知

excel - EXCEL VBA : Listview object feature not found when exporting XLAM file to another machine

c# - 使用 DisplayFor 启用 CheckBox

c# - 发现环境颜色背后的真实颜色

c# - 在 C# 中使用字符串和接口(interface)的字典

c# - 统一蹲下时,旋转播放器上的相机晃动

c# - Unity3D - 我可以使用 .NET 4.5 程序集作为外部库吗?

c# - 随机选择一些数字c#