유니티 심화/복습

[복습] SpaceShooter2D - Player, Bullet -> Main으로 옮기기, 오브젝트 풀링 기반 만들기

다모아 2023. 8. 28. 20:42

BulletController

using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;

public class BulletController : MonoBehaviour
{
    [SerializeField]
    private float force = 3f;
    private GameObject targetTr;

    // Start is called before the first frame update
    void Start()
    {
        this.targetTr = this.GetComponent<GameObject>();
        this.targetTr = GameObject.Find("Player");
        this.transform.position = this.targetTr.transform.position + this.targetTr.transform.up * 0.5f;
    }

    private void Update()
    {
        this.transform.Translate(Vector2.up * this.force * Time.deltaTime);

        if(this.transform.position.y >= 4.85f)
        {
            //총알 비활성화
            BulletPoolManager.instance.Release(this.gameObject);
        }
    }
}

 

BulletPoolManager

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BulletPoolManager : MonoBehaviour
{
    public static BulletPoolManager instance;
    //리스트로 풀 만들기
    public List<GameObject> bulletPool = new List<GameObject>();
    //총알 프리팹
    [SerializeField]
    private GameObject bulletGo;
    //최대 몇개치까지 만들건지
    private int maxBullets = 20;

    private void Awake()
    {
        instance = this;
        DontDestroyOnLoad(this.gameObject);
    }

    // Start is called before the first frame update
    void Start()
    {
        for(int i = 0; i < this.maxBullets; i++)
        {
            //인스턴스 생성
            GameObject bullet = Instantiate(this.bulletGo);
            //어디에?
            bullet.transform.SetParent(this.transform);
            //비활성화
            bullet.SetActive(false);
            //리스트에 추가
            this.bulletPool.Add(bullet);
        }    
    }

    public GameObject GetBullet()
    {
        //리스트에 순차확인
        foreach(GameObject bullet in bulletPool)
        {
            //활성화가 되있냐?
            if(bullet.activeSelf == false)
            {
                //null로 활성화 되면 해주기
                bullet.transform.SetParent(null);
                //bullet 리턴
                return bullet;
            }
        }
        //없으면 null 리턴
        return null;
    }

    public void Release(GameObject bullet)
    {
        //비활성화
        bullet.SetActive(false);
        //어디에?
        bullet.transform.SetParent(this.transform);
    }
}

 

EnumState

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnumState
{
    public enum ePlayerState
    {
        Center, Left, Right
    }
}

 

SpaceShooter2DMain

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpaceShooter2DMain : MonoBehaviour
{
    //플레이어
    [SerializeField]
    private PlayerController playerController;
    //총알
    [SerializeField]
    private BulletController bulletController;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        //플레이어 움직이기
        this.playerController.Move();

        //왼쪽 방향키 누르면 애니메이션 왼쪽 실행
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            this.playerController.PlayAnimation(EnumState.ePlayerState.Left);
        }
        //오른쪽 방향키 누르면 애니메이션 오른쪽 실행
        else if (Input.GetKey(KeyCode.RightArrow))
        {
            this.playerController.PlayAnimation(EnumState.ePlayerState.Right);
        }
        //아무것도 아니라면 애니메이션 센터 실행
        else
        {
            this.playerController.PlayAnimation(EnumState.ePlayerState.Center);
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            //총알 소환
        }
    }
}

 

PlayerController

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    [SerializeField]
    private float moveSpeed = 3f;

    private Animator anim;
    // Start is called before the first frame update
    void Start()
    {
        this.anim = this.GetComponent<Animator>();
    }

    public void Move()
    {
        //움직이고 화면가두기
        float h = Input.GetAxisRaw("Horizontal");
        float v = Input.GetAxisRaw("Vertical");

        Vector2 moveDir = (Vector2.up * v) + (Vector2.right * h);
        this.transform.Translate(moveDir.normalized * this.moveSpeed * Time.deltaTime);

        float clampX = Mathf.Clamp(this.transform.position.x, -2.30f, 2.30f);
        float clampY = Mathf.Clamp(this.transform.position.y, -4.50f, 4.50f);

        this.transform.position = new Vector2(clampX, clampY);
    }

    public void PlayAnimation(EnumState.ePlayerState state)
    {
        this.anim.SetInteger("State", (int)state);
    }
}

 

영상은 딱히 달라진건 없음..