오류 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;
}
}
조금 더 안전하게 사용가능!
'Today I Learn' 카테고리의 다른 글
25/04/30 | TIL Ref와 Out정의하기 (0) | 2025.04.30 |
---|---|
25/04/29 | TIL RayCast 재정의하기 (0) | 2025.04.29 |
25/04/18 | TIL 바로인턴 11기 과제 정리 (0) | 2025.04.19 |
25/04/17 | TIL 바로인턴 11기 신청 및 OT내용정리 (1) | 2025.04.18 |
25/04/07 | TIL 알고리즘3 - A*알고리즘과 이진힙구조 (0) | 2025.04.07 |