문제 상황 : 실행버튼만 눌렀다하면 오브젝트에 넣어둔 script component가 지혼자 이유없이 꺼져버림
해결 : 지혼자 꺼지는 스크립트의 Awak() 안에 있는 코드 중 null로 반환되는 코드가 있는지 찾아보기
스크립트에 Component.enable=false; 하는 코드도 없는데 지혼자 꺼지고 있다. Unity를 껐다 켜봐도 그대로.
그러나 정답은 언제나 Consol에 있다
↓ 아래가 문제의 코드 ↓
CharacterController characterController;
public PlayerStatus pStatus;
GameObject zombieObj;
ZombieAI zombieAI;
void Awake()
{
characterController = GetComponent<CharacterController>();
pStatus = GetComponent<PlayerStatus>();
// 문제의 코드 부분(Null 반환 중)
zombieObj = GameObject.FindGameObjectWithTag("Zombie");
zombieAI = zombieObj.GetComponent<ZombieAI>();
}
테스트할 때마다 좀비가 달려드는 게 귀찮아서 Zombie 태그가 붙은 오브젝트를 다 꺼둔 것이 원인.
좀비태그 붙은 오브젝트를 못 찾음 -> zombieAI에 할당할 오브젝트가 없음 => NullReferenceException 발생
When play Unity, script component is false 이러고 구글링 했는데 그냥 콘솔만 잘 읽었어도 해결될 문제였다.
그래도 구글링으로 얻은 수확 : 이런 코드는 Awake에 두지 말고 Start에 넣어두면 에러떠도 component가 꺼지지는 않는다.
CharacterController characterController;
public PlayerStatus pStatus;
GameObject zombieObj;
ZombieAI zombieAI;
void Awake()
{
characterController = GetComponent<CharacterController>();
pStatus = GetComponent<PlayerStatus>();
}
void Start()
{
// 문제의 코드 부분(Null 반환 중)
zombieObj = GameObject.FindGameObjectWithTag("Zombie");
zombieAI = zombieObj.GetComponent<ZombieAI>();
}
이러면 console에 에러 문구는 뜨지만 스크립트가 꺼지지는 않는다.
그래도 베스트는 null일 때에 대한 대책 코드를 넣는 것(warning, error는 있어서 하등 좋을 게 없다)
CharacterController characterController;
public PlayerStatus pStatus;
GameObject zombieObj;
ZombieAI zombieAI;
void Awake()
{
characterController = GetComponent<CharacterController>();
pStatus = GetComponent<PlayerStatus>();
}
void Start()
{
// 문제의 코드 부분(Null 반환 중)
if(GameObject.FindGameObjectWithTag("Zombie") != null){
zombieObj = GameObject.FindGameObjectWithTag("Zombie");
zombieAI = zombieObj.GetComponent<ZombieAI>();
}
}
'게임개발 > 스마게챌린지3기 & 수요백화점' 카테고리의 다른 글
[Unity] 쿼터뷰 카메라 - 물체 무시 (0) | 2024.05.02 |
---|---|
[Unity] box collider does not support negative scale or size (0) | 2022.05.10 |