728x90
일반 몬스터들은 오브젝트 풀링을 활용한 총알을 몇 번 쏘기도 전에 플레이어에 의해 destroy 되어서 문제를 느끼지 못하고 있었는데, 보스 몬스터를 구현하다 보니 오브젝트 풀링으로 구현한 총알이 자꾸 활성화 되자마자 다시 사라지는 문제가 생겼다.
문제의 원인은 큐에 이미 있는 총알을 다시 큐에 집어넣으려는 시도 때문에 발생했다.
public void FindPlayer()
{
if(!dead && Time.time >= lastAttackTime + timeBetAttack)
{
Collider[] other = Physics.OverlapSphere(transform.position, 9f, whatIsTarget);
if(other.Length >=1)
{
LivingEntity attackTarget = other[0].GetComponent<LivingEntity>();
if (attackTarget != null && attackTarget == targetEntity)
{
lastAttackTime = Time.time;
GameObject bullet = bulletQ.Dequeue();
bullet.SetActive(true);
bullet.transform.position = transform.position +Vector3.up;
bullet.transform.LookAt(attackTarget.transform.position);
bullet.GetComponent<Rigidbody>().velocity = new Vector3(0,0,0);
bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * speed;
bullet.GetComponent<Bullet>().off +=()=> Add(bullet);
bullet.GetComponent<Bullet>().off +=()=> bullet.SetActive(false);
enemyAudioPlayer.PlayOneShot(attackSound);
enemyAnimator.SetTrigger("Attack");
}
}
}
}
private void Add(GameObject bullet)
{
if(!bulletQ.Contains(bullet))
bulletQ.Enqueue(bullet);
}
기존의 코드를 봐도 왜 이미 큐에 있는 총알 오브젝트에 다시 Enqueue하게 되는지는 이해할 수 없었다.
어쨌든 위 코드 중 Add(GameObject bullet) 함수를 이용해서 오브젝트가 이미 큐에 있는지 확인(Contains 활용), 큐에 없다면 Enqueue 하도록 전체 코드를 수정했다. 이후로 총알이 활성화 되자마자 사라지거나, 제대로 활성화되지 않는 오류가 사라졌다.
728x90
'Unity' 카테고리의 다른 글
[Unity] 오브젝트 풀링 + 가장 가까운 적 방향으로 공격 (0) | 2022.04.22 |
---|---|
[Unity] 화염 방사 아이템 (0) | 2022.04.12 |
[Unity] 퍼블릭(public) 선언시 주의할 점 (0) | 2022.04.07 |
[Unity] 로그라이크 개발 - 아이템 강화 시스템 실패 (0) | 2022.03.31 |
[Unity] 가장 가까운 적에게 투사체 발사 (0) | 2022.03.27 |