인프런 강의 - 케이디 생존게임

케이디 강의8 - (매니저 스크립트 생성/ 무기변경, 상태에 따른 모션 변경)

WMG1 2022. 11. 12. 21:32
반응형

 

public class WeaponManager : MonoBehaviour
{
    // 무기 중복 교체 실행 방지.
    public static bool isChangeWeapon = false; //static 공유 자원. 클래스 변수 = 정적 변수
                                               //모든 객체에 값을 달리 줄 필요가 없는경우 사용

    //현재 무기와 현재 무기의 애니메이션
    public static Transform currentWeapon; //역할 : 무기 가려주기(무기 스왑 시) 끝
    public static Animator currentWeaponAnim;



    //현재 무기의 타입
    [SerializeField]
    private string currentWeaponType;



    //무기 교체 딜레이타임
    [SerializeField]
    private float changeWeaponDelayTime; //무기 교체 중
    [SerializeField]
    private float changeWeaponEndDelayTime; //무기 교체 완료시점


    //무기 종류 관리
    [SerializeField]
    private Gun[] guns; //무기 배열
    [SerializeField]
    private Hand[] hands; // 맨손 배열(너클 맨손 등등)


    //(딕셔너리 선언, 생성) 관리차원에서 쉽게 무기접근이 가능해짐
    private Dictionary<string, Gun> gunDictionary = new Dictionary<string, Gun>();
    private Dictionary<string, Hand> handDictionary = new Dictionary<string, Hand>();


    //필요한 컴포넌트
    //상태에 따라 한쪽을 끄고 한쪽을 활성화 할 수있게 선언
    [SerializeField]
    private GunController thegunController; //총일 때 활성화
    [SerializeField]
    private HandController thehandController; //맨손을 활성화 







    void Start()
    {
        for (int i = 0; i < guns.Length; i++) // 0인 i가 총 배열의 끝까지 가도록 반복
        {
            gunDictionary.Add(guns[i].gunName, guns[i]); // 키값guns의 총 이름, 총기 순서값)
        }
        for (int i = 0; i < hands.Length; i++)
        {
            handDictionary.Add(hands[i].handName, hands[i]); // 키값hands의 총 이름, 맨손 순서값)
        }
        
    }

    // Update is called once per frame
    void Update()
    {
        if(!isChangeWeapon)
        {
            if (Input.GetKeyDown(KeyCode.Alpha1)) //숫자1이 눌렸을 경우
                StartCoroutine(ChangeWeaponCoroutine("HAND", "맨손")); //코루틴 시작, 타입과 이름 입력

            else if (Input.GetKeyDown(KeyCode.Alpha2)) //숫자2이 눌렸을 경우
                StartCoroutine(ChangeWeaponCoroutine("GUN", "SubMachineGun1"));

        }
    }

    //무기 교체 코루틴
    public IEnumerator ChangeWeaponCoroutine(string _type, string _name) //인수 넘겨주기 현재 무기타입, 총종류
    {
        isChangeWeapon = true; //무기교체 중복실행 방지
        currentWeaponAnim.SetTrigger("Weapon_Out"); //무기 넣기 애니

        yield return new WaitForSeconds(changeWeaponDelayTime); //무기교체 딜레이 만큼 대기

        CancelPreWeaponAction(); //기존(이전) 무기 취소
        WeaponChange(_type, _name); // 실제 무기 교체

        yield return new WaitForSeconds(changeWeaponEndDelayTime); //무기교체 종료시간 만큼 대기

        currentWeaponType = _type; // 현재 무기 타입을 바꾸고자 할 타입으로 변경
        isChangeWeapon = false; //무기 교체가 끝난 시점에 / 무기교체 상태를 거짓으로 만들어 무기교체 가능하게 해줌
    }


    //현재 무기 동작 정지
    private void CancelPreWeaponAction() 
    {
        switch(currentWeaponType) // 조건문이랑 같은 기능임 if,else if
        {
            case "GUN": //조건
                thegunController.CanCelFineSight();
                thegunController.CancelReload();//결과
                GunController.isActivate = false;
                break;
            case "HAND":
                HandController.isActivate = false;
                break;
        }
    }

    private void WeaponChange(string _type, string _name)
    {
        if(_type == "GUN")
            thegunController.GunChange(gunDictionary[_name]);
        
        else if(_type == "HAND")
            thehandController.HandChange(handDictionary[_name]);
    }

}

이번 시간에 작성한 스크립트

 

코루틴을 통해 무기 교체 중복 실행을 방지하였고

Dictionary 선언을 통한 쉬운 배열 관리를 배웠다.

[*Dictionary를 자유롭게 사용하기 위해선 좀 더 검색 후 공부해 봐야겠음]

 

switch문도 새로 배웠다.

기능적으로 if , else if 와 다를 것이 없었지만

상황에 따라서 if문 보다 훨씬 깔끔한 코드 정리를 할 수 있을 듯하다.

 

웨폰 매니저에서 전체적인 총기, 맨손 등의 현재 무장 상태를 알게 하고 무기 교체를 관리하였다.

 

행동 애니메이션은 Crosshair 스크립트에서 이미 다루고 있으므로

해당 함수에

 

   public void RunningAnimation(bool _flag) 
    {
        **WeaponManager.currentWeaponAnim.SetBool("Run", _flag);**
        animator.SetBool("Running", _flag);
    }

 

이런 식으로 애니메이션 파라미터 조정 코드를 넣어서 구현하였다.

 

경사로 애니메이션 출력 이슈는

    public void JumpingAnimation(bool _flag)
    {       
        animator.SetBool("Running", _flag);
    }

 

플레이어 컨트롤러 스크립트에서

isGround 함수에

 

 theCrosshair.JumpingAnimation(!isGround); 추가

해당 코드로 해결하였다

 

 

강의 중 새롭게 안 코드나 기능들은 따로 메모장에 계속 기입 중이다.

반응형