반응형

이번시간에는 총알이 계속 생성되고 삭제되면 메모리 누수현상이 일어나는 것을 방지 하기 위한 프로그램을 짜보겠습니다

그림과 같이 비행기 총알을 만들고 계속 삭제 하다 보면 기기에 메모리 누수 현상으로 기기에 무리를 가하게 됩니다

그래서 memory pool을 만들어 활용 하겠습니다

이것은 총알 뿐만 아니라 다른 이팩트나 적을 생성 할때도 같이 활용합니다 



빈 게임오브젝트를 만들어 ObjectManager라 이름 붙힘니다


ObjectManager 스크립트를 만듭니다




ObjectManager 스크립트를 오브젝트에 붙힘니다


ObjectManager 스크립트작성



using System.Collections;

using System.Collections.Generic;

using UnityEngine;


public class ObjectManager : MonoBehaviour

{

    public static ObjectManager instance;


    public GameObject rocketPrefab;


    List<GameObject> bullets = new List<GameObject>();// 총알을 담아둘 리스트를 만듬


    private void Awake()

    {

        if (ObjectManager.instance == null)

        {

            ObjectManager.instance = this;

        }

    }

    void Start ()

    {

        CreateBullets(5); //총알 5개를 생성

}

    void CreateBullets(int bulletCount)

    {

        for (int i = 0; i <  bulletCount; i++)

        {     

            // Instantiate()로 생성한 게임 오브젝트를 변수에 담고자 하면 ,"as + 데이터타임"을 명령어 뒤어 붙여 주어야 함

            GameObject bullet = Instantiate(rocketPrefab) as GameObject;


            bullet.transform.parent = transform;

            bullet.SetActive(false);


            bullets.Add(bullet);

        }

    }

    public GameObject GetBullet(Vector3 pos)

    {

        GameObject reqBullet = null;

        for (int i = 0; i < bullets.Count; i++) 

        {

            if (bullets[i].activeSelf == false)

            {

                reqBullet = bullets[i];// 비활성화 되어있는 총알을 찾아 reqBullet에 담아둠니다


                break;

            }

        }


        if (reqBullet == null)// 추가 총알 생성

        {

            GameObject newBullet = Instantiate(rocketPrefab) as GameObject;

            newBullet.transform.parent = transform;


            bullets.Add(newBullet);

            reqBullet = newBullet;

        }


        reqBullet.SetActive(true); //reqBullet활성


        reqBullet.transform.position = pos;


        return reqBullet;

    }

void Update () {

}

}







메모리 플 스크립트를 작성 하였습니다

메모리 플 스크립트를 총알에 활둉하기 위하여 총알과 연관되어 있는 스크립트를 수정하여야 합니다



Player 스크립트를 엽니다




그림과 같이 스크립트를 수정합니다


Rocket스크립트를 엽니다 




Rocket 스크립트를 수정합니다


Enemy 스크립트를 엽니다


그림과 같이 Enemy 스크립트를 수정합니다


게임을 실행하여 총알의 메모리 풀이 제대로 동작하는지 확인합니다

이번시간은 총알을 활용한 메모리 풀을 만들어 보았는데 같은 방법으로 적기나 이팩트를 메모리 풀로 활용하면 데이터 메모리 누수를 막을 수 있습니다 

 


반응형

+ Recent posts