我正在尝试创建一个保存级别系统,并且继续出现此错误。
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/