다음과 같은 에러가 발생했습니다
NullReferenceException: Object reference not set to an instance of an object ScrollingObject.Update () (at Assets/Scripts/ScrollingObject.cs:10)
특정 변수나 객체에 유효한 인스턴스가 할당되지 않은 상태에서 해당 객체를 사용하려고 할 때 발생한다고 들었습니다
에러 발생 코드는 다음과 같습니다
void Awake() {
// 싱글톤 변수 instance가 비어있는가?
if (instance == null)
{
// instance가 비어있다면(null) 그곳에 자기 자신을 할당
instance = this;
}
else
{
// instance에 이미 다른 GameManager 오브젝트가 할당되어 있는 경우
// 씬에 두개 이상의 GameManager 오브젝트가 존재한다는 의미.
// 싱글톤 오브젝트는 하나만 존재해야 하므로 자신의 게임 오브젝트를 파괴
Debug.LogWarning("씬에 두개 이상의 게임 매니저가 존재합니다!");
Destroy(gameObject);
}
**StartTutorials.SetActive(true);
StartTutorials2.SetActive(true);
Pause();
if (!gameStarted && Input.GetKeyDown(KeyCode.Space))
{
StartTutorials.SetActive(false);
StartTutorials2.SetActive(false);
StartGame();
gameStarted = true;
}**
}
다음 코드를 아래와 같이 수정한 결과 해결 했습니다.
static CLASS instance;
// 게임 시작과 동시에 싱글톤을 구성
void Awake() {
// 싱글톤 변수 instance가 비어있는가?
if (instance == null)
{
// instance가 비어있다면(null) 그곳에 자기 자신을 할당
instance = this;
}
else
{
// instance에 이미 다른 GameManager 오브젝트가 할당되어 있는 경우
// 씬에 두개 이상의 GameManager 오브젝트가 존재한다는 의미.
// 싱글톤 오브젝트는 하나만 존재해야 하므로 자신의 게임 오브젝트를 파괴
Debug.LogWarning("씬에 두개 이상의 게임 매니저가 존재합니다!");
Destroy(gameObject);
}
}
void Start()
{
StartTutorials.SetActive(true);
StartTutorials2.SetActive(true);
Pause();
}
public void Pause()
{
Time.timeScale = 0;
}
public void StartGame()
{
Time.timeScale = 1;
}
void Update() {
if (!gameStarted&& Input.GetKeyDown(KeyCode.Space))
{
StartTutorials.SetActive(false);
StartTutorials2.SetActive(false);
StartGame();
gameStarted = true;
}
// 게임 오버 상태에서 게임을 재시작할 수 있게 하는 처리
if (isGameover && Input.GetKeyDown(KeyCode.Space))
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
에러를 추정을 해볼 때, Awake()메소드에 작성을 해서 싱글턴 패턴 구현에 간섭이 생겨서 에러가 발생 한 것으로 추정하고 있습니다.
정확한 요인과 해결방법이 바람직한지 궁금합니다…..!