Today I Learn

25/04/28 | TIL 3D Survival 재수강 - Singleton

오늘도즐겨 2025. 4. 28. 23:44

오류 NullReference Error

 

내가 작업을 하면서 가장 많이 겪는 오류....

 

instance = null로 작성하여 대입을 해버림;

if문 안에는 조건문이 들어가야하거늘!!!!!!!!

왜 이런 기본적인 실수를... 했을까 ㅠ

 

그래서 instance = null이 되어버리고, 항상 null로 덮어쓰기 때문에,
new GameObject("CharacterManager")가 만들어지는 로직이 실행되지 않는다.

 

public static CharacterManager Instance
{
    get 
    {
        if (instance == null)
        {
            instance = new GameObject("CharacterManager").AddComponent<CharacterManager>();
        }
        return instance;
    }
}

 

추가 활용예시

Awake()에서 DontDestroyOnLoad(gameObject)를 쓰는 것은 좋지만,

private void Awake()
{
    if (instance == null)
    {
        instance = this;
        DontDestroyOnLoad(gameObject);
    }
    else
    {
        if (instance != this)
        {
            Destroy(gameObject);
        }
    }
}


Instance를 통해 강제로 생성할 때는 Awake가 호출되지 않을 수 있음

지금 구조는 기본적으로 CharacterManager가 씬에 미리 존재하는 것을 가정하고 있음


만약 정말 어디서든 보장 없이 사용할 거라면

Instance 안에서 직접 Awake 역할까지 하도록 보완할 수도 있다

public static CharacterManager Instance
{
    get 
    {
        if (instance == null)
        {
            instance = new GameObject("CharacterManager").AddComponent<CharacterManager>();
            DontDestroyOnLoad(gameObject);
        }
        return instance;
    }
}

 

조금 더 안전하게 사용가능!