繁体   English   中英

UnityException:不允许从 MonoBehaviour 构造函数调用 GetActiveScene

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

我正在尝试制作一个保存级别系统,但我不断收到此错误。

UnityException:不允许从 MonoBehaviour 构造函数调用 GetActiveScene

我试过搜索这个,但没有结果。 这是我使用的代码:

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()方法中获取当前活动场景。

Start()示例:

private int sceneNumber;

private void Start() {
    sceneNumber = SceneManager.GetActiveScene().buildIndex;
}

作为替代解决方案,您还可以使用 Lazzy Getter。 这意味着该值在场景加载和使用之间不会过时,这可能与其他数据片段有关。

使用 Lazzy Getter 的示例:

private int sceneNumber { 
    get { 
        return SceneManager.GetActiveScene().buildIndex; 
    }
}

当您使用这些解决方案中的任何一个时,您现在只需在SceneManager.Load()函数调用中调用scenenumber + 1即可。

此外,您需要确保您正在调用IEnumerator ,而不是调用函数调用。 如果你想延迟场景加载。

函数调用:

private void OnCollisionEnter (Collision collisionInfo) {
    ...
    StartCoroutine(NextLevel(3f));
    ...
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM