상세 컨텐츠

본문 제목

유니티 총 재장전

유니티/기능

by MJ_119 2024. 8. 16. 02:24

본문

총 재장전 할때 개수 확인하기.

 

- Gun Controller 스크립트에 있는 getGun() 함수를 통해 현재 사용중인 Gun을 가져온다.

    public Gun getGun()
    {
        return currentGun;
    }
IEnumerator ReloadCoroutine()
    {
        if ( currentGun.carryBulletCount > 0 )
        {
            isReload = true;

            characterControllerMove.animator.SetTrigger("Reload");

            yield return new WaitForSeconds(currentGun.reloadTime);

            // 현재 가지고있는 총알을 버리지 않고 합쳐서 재장전하기

            int totalBullet = currentGun.currentBulletCount + currentGun.carryBulletCount;

            // 재장전할 수 있는 최대 총알 수
            if (totalBullet >= currentGun.reloadBulletCount)
            {
                // 탄창을 가득 채우고 나머지를 예비 총알로 남김
                currentGun.currentBulletCount = currentGun.reloadBulletCount;
                currentGun.carryBulletCount = totalBullet - currentGun.reloadBulletCount;
            }
            else
            {
                // 남은 모든 예비 총알을 탄창에 채움
                currentGun.currentBulletCount = totalBullet;
                currentGun.carryBulletCount = 0;
            }

            isReload = false;

        }
        else
        {
            // 총알이 없어서 헛도는 사운드 재생.
            print("총알이 없음");
        }
    }

 

 

 

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

public class GameManager : MonoBehaviour
{
    public static GameManager instance;

    [SerializeField]
    GunController gunController;
    Gun gun;

    [Header("Bullet")]
    [SerializeField]
    private Transform bulletPoint;
    [SerializeField]
    private GameObject bulletObject;

    // 총알 UI
    public TextMeshProUGUI bulletUI;

    void Start()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject); // GameManager를 씬 전환 시에도 유지
        }
        else if (instance != this)
        {
            Destroy(gameObject); // 중복된 GameManager 인스턴스를 파괴
            return;
        }
        gun = gunController.getGun();
    }

    void Update()
    {
        bulletCountUI();
    }


    public void bulletCountUI()
    {
        // int값을 문자열로 전환해서 Text에 띄움
        bulletUI.text = gun.currentBulletCount.ToString() + " / " + gun.carryBulletCount.ToString();
    }

}

 

- Gun Controller 컴포넌트를 가지고있는 캐릭터를 드래그해서 게임 매니저 스크립트에 넣어준다.

 

 

 

 

관련글 더보기