상세 컨텐츠

본문 제목

유니티 아이템,총알 습득하기

유니티/기능

by MJ_119 2024. 9. 16. 18:48

본문

- 아이템 기본 구성 : 빈오브젝트 프리팹으로 만들고 하위 계층에 아이템 오브젝트( ex.큐브 )만들고 하위 오브젝트에 있는 box 콜라이더 컴포넌트는 해제하고, 상위에 있는 bullet_PickUp에 스크립트와 콜라이더를 넣고 트리거를 킨다.

 

using UnityEngine;

public class PickUp : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        if( other.CompareTag("Player"))
        {
            print("wwwww");
            Destroy(gameObject);
        }
    }
}

 

 

- 아이템 획득시 증가할 총알 종류와 총알 개수를 아이템에 스크립트로 넣는다.

- 플레이어가 가지고있는 Ammo 스크립트에 IncreaseCurrentAmmo(AmmoType ammoType, int ammoAmount) 함수를 만들고 아이템에 Trigger 했을때 함수를 실행한다.

 

아이템 스크립트

using UnityEngine;

public class PickUp : MonoBehaviour
{
    [SerializeField] int ammoAmount = 5;
    [SerializeField] AmmoType ammoType;

    private void OnTriggerEnter(Collider other)
    {
        if( other.CompareTag("Player"))
        {
            other.GetComponent<Ammo>().IncreaseCurrentAmmo(ammoType,ammoAmount);
            Destroy(gameObject);
        }
    }
}

 

 

AmmoType 스크립트

public enum AmmoType
{
    Bullets,
    Shells,
    Rockets
}

 

Ammo 스크립트

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

public class Ammo : MonoBehaviour
{
    [SerializeField] AmmoSlot[] ammoSlots;

    [Serializable]
    private class AmmoSlot
    {
        public AmmoType ammoType;
        public int ammoAmount;
    }


    public int GetCurrentAmmo(AmmoType ammoType)
    {
        return GetAmmoSlot(ammoType).ammoAmount;
    }
    public void ReduceCurrentAmmo(AmmoType ammoType)
    {
        GetAmmoSlot(ammoType).ammoAmount--;
    }

    public void IncreaseCurrentAmmo(AmmoType ammoType, int ammoAmount)
    {
        GetAmmoSlot(ammoType).ammoAmount += ammoAmount;
    }

    private AmmoSlot GetAmmoSlot(AmmoType ammoType)
    {
        foreach(AmmoSlot slot in ammoSlots)
        {
            if (slot.ammoType == ammoType)
                return slot;
        }
        return null;
    }
}

 

 

 

 

관련글 더보기