我通过在线课程工作并获得Null引用异常。我知道这是一个非常常见的错误,但无论是我还是课程的在线帮助都无法解决这个问题。所以我希望你能给我一些启发。
关卡管理脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelManager : MonoBehaviour
{
[SerializeField] float sceneLoadDelay = 2f;
ScoreKeeper scoreKeeper;
void Start()
{
scoreKeeper = FindObjectOfType<ScoreKeeper>();
}
public void LoadGame()
{
scoreKeeper.ResetScore();
SceneManager.LoadScene("MainGame");
}
public void LoadMainMenu()
{
SceneManager.LoadScene("MainMenu");
}
public void LoadGameOver()
{
StartCoroutine(WaitAndLoad("GameOver", sceneLoadDelay));
}
public void QuitGame()
{
Debug.Log("Quitting Game...");
Application.Quit();
}
IEnumerator WaitAndLoad(string sceneName, float delay)
{
yield return new WaitForSeconds(delay);
SceneManager.LoadScene(sceneName);
}
}
Score Keeper Script:
public class ScoreKeeper : MonoBehaviour
{
int score;
static ScoreKeeper instance;
void Awake()
{
ManageSingleton();
}
void ManageSingleton()
{
if (instance != null)
{
gameObject.SetActive(false);
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
}
}
public int GetScore()
{
return score;
}
public void ModifyScore(int value)
{
score += value;
Mathf.Clamp(score, 0, int.MaxValue);
Debug.Log(score);
}
public void ResetScore()
{
score = 1;
}
}
错误出现在关卡管理器的这一行:我应该补充的是,关卡管理器和分数保存器对象是与脚本一起创建的,并且在每个场景中。
在层次结构寻找至少2个GameObjects是否存在
- 一个与ScoreKeeper.cs在
- 另一个与LevelManager.cs在
如果这是ok的,那么打开LevelManager.cs并添加privateScoreKeeper;因为你已经在Start()中找到并附加了它方法,如下所示
private ScoreKeeper scoreKeeper;
问题是你需要调用ScoreKeeper.instance.ResetScore()。你把它设置为单例。否则你就需要在关卡管理器中添加一个实例的具体引用。
您还需要将实例设为public:
public static ScoreKeeper instance;