Unity

[Unity] 오브젝트 풀링시 총알이 자꾸 사라지는 문제

Yannoo 2022. 5. 17. 20:22
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