![](/img/trans.png)
[英]UnityException: get_time is not allowed to be called from MonoBehaviour constructor
[英]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.