티스토리 뷰

* 만들어 놓은 UIShop을 팀원이 멋지게 만들어 놓은 UIInventory와 연동하는 작업,

드랍된 아이템, UIInventory와 연동을 했다.

먼저 서로 상호 작용하는 경우를 생각해 봤다.  

 

 

 

*UIShop , UIInventory와 연동

1. 상점에서 구입한 아이템이 인벤토리에서 "Cell" 형식으로 생성이된다

    - 인벤토리 용량을 체크한 후 용량이 있다면 생성, 용량이 없다면 생성되지 않는다

2. 인벤토리에 아이템이 잘 들어갔다면? 캐릭터의 능력치가 향상이된다

    - UIShop => UIInventory => Player 순으로 이벤트 디스패쳐를 통해 전달된다.

 

*UIShop , UIInventory와 연동 // 상점에서 아이템을 구입 (인벤토리 용량을 체크하는 상호작용)

 

 

*드랍된 아이템, UIInventory와 연동

1. 던전 룸을 클리어 한다면 ? 보상상자가 생성 => 플레이어와 충돌하면 아이템이 생성 =>

     플레이어의 인벤토리 용량을 체크한 후, 여유 공간이 있다면? 인벤토리에 추가(Destroy), 없다면 아무 반응하지않음. 

 

*테스트 용으로 상자에서 는 4개의 아이템이 생성되게 만들었다. 생성된 아이템 4개를 습득하려는 플레이어의 인벤토리 용량은 2칸이 남았다. 두개의 아이템을 먹고 두개는 파괴되지않았다 테스트 성공

 

2. 어제 만들어 놓은 연출에서 수정이 필요해서 Chest 에서 생성되는 로직, 인벤토리에서 버리기 로직을 수정했다.

    UIInventory 에서 버리기 버튼을 누른다면 플레이어 주변 (Random.insideUnitSphere * radius)에서 랜덤한 위치에서 생      성 (플레이어와 어느정도 간격을 유지하게 수정이 필요하다. 생성과 동시에 플레이와 충돌 한 후 Destroy되는 경우가있      다)

 

*Random.insideUnitSphere * radius   2f반경의 범위에서 랜덤한 vector 생성.

 

 

 

*생성 로직만 수정한 스크립트 (ChestItemGenerator)

using GooglePlayGames.BasicApi;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.UI;

public class ChestItemGenerator : MonoBehaviour
{
    [SerializeField] private GameObject WoodChest;
    [SerializeField] private GameObject IronChest;
    [SerializeField] private GameObject GoldChest;
    [SerializeField] private GameObject DiamondChest;
    [SerializeField] private GameObject dropItem;
    private ShopFactory factory;

    public void Init()
    {
        this.factory = this.gameObject.GetComponent<ShopFactory>();
        EventDispatcher.Instance.AddListener<Transform, bool>(EventDispatcher.EventName.ChestItemGeneratorMakeChest,
            this.MakeChset);
        EventDispatcher.Instance.AddListener<Transform, string>(EventDispatcher.EventName.ChestItemGeneratorMakeItemForChest,
            this.MakeItemForChest);
        EventDispatcher.Instance.AddListener<string>(EventDispatcher.EventName.ChestItemGeneratorMakeItemForInventory,
            this.MakeItemForInventory);
    }

    /// <summary>
    /// 체스트를 생성합니다. ( 보스일경우 2번째 인자값 true)
    /// </summary>
    /// <param name="callPosition"> 상자 생성 위치</param>
    /// <param name="isBoss">보스방 상자 인지 아닌지</param>
    private void MakeChset(Transform callPosition , bool isBoss = false)
    {
        Debug.Log("맵이 상자 만들어 달래");
        Debug.LogFormat("위치 : {0} , 보스방? : {1}", callPosition.position, isBoss);
        var setp = InfoManager.instance.dungeonInfo.currentStepInfo;
        if (!isBoss)
        {
            if (setp < 4)
            {
                var go = GameObject.Instantiate(this.WoodChest, callPosition);
                go.name = go.name.Replace("(Clone)","");
                go.transform.localPosition = Vector2.zero;   
            }
            else if (setp > 3 && setp < 10)
            {
                var go = GameObject.Instantiate(this.IronChest, callPosition);
                go.name = go.name.Replace("(Clone)","");
                go.transform.localPosition = Vector2.zero;
            }
            else if (setp > 9)
            {
                var go = GameObject.Instantiate(this.GoldChest, callPosition);
                go.name = go.name.Replace("(Clone)","");
                go.transform.localPosition = Vector2.zero;
            }
        }
        else
        {
            var go = GameObject.Instantiate(this.DiamondChest, callPosition);
            go.name = go.name.Replace("(Clone)","");
            go.transform.localPosition = Vector2.zero;
        }
    }

    /// <summary>
    /// 상자의 콜에 의해 아이템을 생성합니다.(NPCController)
    /// </summary>
    /// <param name="callPosition">상자의 위치</param>
    /// <param name="chestName">상자의 이름 (예 : Wood_Chest)</param>
    private void MakeItemForChest(Transform callPosition, string chestName)
    {
        Debug.Log("상자가 아이템 만들래"); //NPCController
        Debug.LogFormat("포지션 : {0} , 이름 : {1}", callPosition.position, chestName);
        //아이템을 만든다
        if (chestName == "Wood_Chest")
        {
            int idx = 4;
            for (int i=0; i< idx; i++) //Test - 4개 생성
            {
                int ran = Random.Range(0, 5);
                var dropItemGo = Instantiate(this.dropItem, callPosition);

                Vector3 playerPosition = callPosition.position;
                float radius = 2f;
                Vector3 randomPosition = playerPosition + Random.insideUnitSphere * radius;
                dropItemGo.transform.position = randomPosition;

                //dropItemGo.transform.position = callPosition.position;
                var imgDropItem = dropItemGo.GetComponent<SpriteRenderer>().sprite;
                switch (ran)
                {
                    case 0:
                        var WoodSwordGo = this.factory.CreatShopSword("Wood", callPosition);
                        var woodSwordSp = WoodSwordGo.transform.GetChild(1).GetComponent<Image>();
                        imgDropItem = woodSwordSp.sprite;
                        Debug.LogFormat("{0}", imgDropItem.name);
                        dropItemGo.tag = WoodSwordGo.tag;
                        Debug.LogFormat("type:{0}", dropItemGo.tag);
                        break;
                    case 1:
                        var WoodAxeGo = this.factory.CreatShopAxe("Wood", callPosition);
                        var woodAxeSp = WoodAxeGo.transform.GetChild(1).GetComponent<Image>();
                        imgDropItem = woodAxeSp.sprite;
                        Debug.LogFormat("{0}", imgDropItem.name);
                        dropItemGo.tag = WoodAxeGo.tag;
                        Debug.LogFormat("type:{0}", dropItemGo.tag);
                        break;
                    case 2:
                        var WoodArrowGo = this.factory.CreatShopArrow("Wood", callPosition);
                        var woodArrowSp = WoodArrowGo.transform.GetChild(1).GetComponent<Image>();
                        imgDropItem = woodArrowSp.sprite;
                        Debug.LogFormat("{0}", imgDropItem.name);
                        dropItemGo.tag = WoodArrowGo.tag;
                        Debug.LogFormat("type:{0}", dropItemGo.tag);
                        break;
                    case 3:
                        var WoodWandGo = this.factory.CreatShopWand("Wood", callPosition);
                        var woodWandSp = WoodWandGo.transform.GetChild(1).GetComponent<Image>();
                        imgDropItem = woodWandSp.sprite;
                        Debug.LogFormat("{0}", imgDropItem.name);
                        dropItemGo.tag = WoodWandGo.tag;
                        Debug.LogFormat("type:{0}", dropItemGo.tag);
                        break;
                    case 4:
                        var IronFooddGo = this.factory.CreatShopFood("Iron", callPosition);
                        var IronFoodSp = IronFooddGo.transform.GetChild(1).GetComponent<Image>();
                        imgDropItem = IronFoodSp.sprite;
                        Debug.LogFormat("{0}", imgDropItem.name);
                        dropItemGo.tag = IronFooddGo.tag;
                        Debug.LogFormat("type:{0}", dropItemGo.tag);
                        break;
                }
                dropItemGo.GetComponent<SpriteRenderer>().sprite = imgDropItem;
            }
            
        }
        if (chestName == "Iron_Chest")
        {
            int idx = 4;
            for (int i = 0; i < idx; i++) //Test - 4개 생성
            {
                int ran = Random.Range(0, 5);
                var dropItemGo = Instantiate(this.dropItem, callPosition);
                dropItemGo.transform.position = callPosition.position;
                var imgDropItem = dropItemGo.GetComponent<SpriteRenderer>().sprite;
                switch (ran)
                {
                    case 0:
                        var WoodSwordGo = this.factory.CreatShopSword("Iron", callPosition);
                        var woodSwordSp = WoodSwordGo.transform.GetChild(1).GetComponent<Image>();
                        imgDropItem = woodSwordSp.sprite;
                        Debug.LogFormat("{0}", imgDropItem.name);
                        dropItemGo.tag = WoodSwordGo.tag;
                        Debug.LogFormat("type:{0}", dropItemGo.tag);
                        break;
                    case 1:
                        var WoodAxeGo = this.factory.CreatShopAxe("Iron", callPosition);
                        var woodAxeSp = WoodAxeGo.transform.GetChild(1).GetComponent<Image>();
                        imgDropItem = woodAxeSp.sprite;
                        Debug.LogFormat("{0}", imgDropItem.name);
                        dropItemGo.tag = WoodAxeGo.tag;
                        Debug.LogFormat("type:{0}", dropItemGo.tag);
                        break;
                    case 2:
                        var WoodArrowGo = this.factory.CreatShopArrow("Iron", callPosition);
                        var woodArrowSp = WoodArrowGo.transform.GetChild(1).GetComponent<Image>();
                        imgDropItem = woodArrowSp.sprite;
                        Debug.LogFormat("{0}", imgDropItem.name);
                        dropItemGo.tag = WoodArrowGo.tag;
                        Debug.LogFormat("type:{0}", dropItemGo.tag);
                        break;
                    case 3:
                        var WoodWandGo = this.factory.CreatShopWand("Iron", callPosition);
                        var woodWandSp = WoodWandGo.transform.GetChild(1).GetComponent<Image>();
                        imgDropItem = woodWandSp.sprite;
                        Debug.LogFormat("{0}", imgDropItem.name);
                        dropItemGo.tag = WoodWandGo.tag;
                        Debug.LogFormat("type:{0}", dropItemGo.tag);
                        break;
                    case 4:
                        var IronFooddGo = this.factory.CreatShopFood("Gold", callPosition);
                        var IronFoodSp = IronFooddGo.transform.GetChild(1).GetComponent<Image>();
                        imgDropItem = IronFoodSp.sprite;
                        Debug.LogFormat("{0}", imgDropItem.name);
                        dropItemGo.tag = IronFooddGo.tag;
                        Debug.LogFormat("type:{0}", dropItemGo.tag);
                        break;
                }
                dropItemGo.GetComponent<SpriteRenderer>().sprite = imgDropItem;
            }
        }
        if (chestName == "Gold_Chest")
        {
            int idx = 4;
            for (int i = 0; i < idx; i++) //Test - 4개 생성
            {
                int ran = Random.Range(0, 5);
                var dropItemGo = Instantiate(this.dropItem, callPosition);
                dropItemGo.transform.position = callPosition.position;
                var imgDropItem = dropItemGo.GetComponent<SpriteRenderer>().sprite;
                switch (ran)
                {
                    case 0:
                        var WoodSwordGo = this.factory.CreatShopSword("Gold", callPosition);
                        var woodSwordSp = WoodSwordGo.transform.GetChild(1).GetComponent<Image>();
                        imgDropItem = woodSwordSp.sprite;
                        Debug.LogFormat("{0}", imgDropItem.name);
                        dropItemGo.tag = WoodSwordGo.tag;
                        Debug.LogFormat("type:{0}", dropItemGo.tag);
                        break;
                    case 1:
                        var WoodAxeGo = this.factory.CreatShopAxe("Gold", callPosition);
                        var woodAxeSp = WoodAxeGo.transform.GetChild(1).GetComponent<Image>();
                        imgDropItem = woodAxeSp.sprite;
                        Debug.LogFormat("{0}", imgDropItem.name);
                        dropItemGo.tag = WoodAxeGo.tag;
                        Debug.LogFormat("type:{0}", dropItemGo.tag);
                        break;
                    case 2:
                        var WoodArrowGo = this.factory.CreatShopArrow("Gold", callPosition);
                        var woodArrowSp = WoodArrowGo.transform.GetChild(1).GetComponent<Image>();
                        imgDropItem = woodArrowSp.sprite;
                        Debug.LogFormat("{0}", imgDropItem.name);
                        dropItemGo.tag = WoodArrowGo.tag;
                        Debug.LogFormat("type:{0}", dropItemGo.tag);
                        break;
                    case 3:
                        var WoodWandGo = this.factory.CreatShopWand("Gold", callPosition);
                        var woodWandSp = WoodWandGo.transform.GetChild(1).GetComponent<Image>();
                        imgDropItem = woodWandSp.sprite;
                        Debug.LogFormat("{0}", imgDropItem.name);
                        dropItemGo.tag = WoodWandGo.tag;
                        Debug.LogFormat("type:{0}", dropItemGo.tag);
                        break;
                    case 4:
                        var IronFooddGo = this.factory.CreatShopFood("Gold", callPosition);
                        var IronFoodSp = IronFooddGo.transform.GetChild(1).GetComponent<Image>();
                        imgDropItem = IronFoodSp.sprite;
                        Debug.LogFormat("{0}", imgDropItem.name);
                        dropItemGo.tag = IronFooddGo.tag;
                        Debug.LogFormat("type:{0}", dropItemGo.tag);
                        break;
                }
                dropItemGo.GetComponent<SpriteRenderer>().sprite = imgDropItem;
            }
        }
    }

    /// <summary>
    /// 인벤토리에서 버려진 아이템을 필드에 생성합니다.
    /// </summary>
    /// <param name="discaredItemName">인벤토리에서 버려진 아이템의 이름</param>
    private void MakeItemForInventory(string discaredItemName)
    {
        Debug.Log("인벤토리가 아이템 만들래"); //Inventory
        Debug.LogFormat("버린 이름 : {0}", discaredItemName);
        
        var playerTrans = GameObject.FindWithTag("Player").transform;
        // 아이템 이름에 맞는 아이템을 생성한다 (아이템 이름은 Wood_Sword)
        var dropGo=Instantiate(this.dropItem);
        dropGo.tag = "Equipment";
        //dropGo.transform.position =  new Vector3(playerTrans.position.x +2, playerTrans.position.y,2) ;

        Vector3 playerPosition = playerTrans.position;
        float radius = 2f;
        Vector3 randomPosition = playerPosition + Random.insideUnitSphere * radius;
        dropGo.transform.position = randomPosition;

        var resultSpriteAtlas = AtlasManager.instance.GetAtlasByName("UIEquipmentIcon");
        var resultSp = resultSpriteAtlas.GetSprite(discaredItemName);
        dropGo.GetComponent<SpriteRenderer>().sprite= resultSp;

        dropGo.transform.localScale = new Vector3(3f, 3f, 3f);
       
        // 이 이름을 그대로 아틀라스 매니저에서 가져와서 쓰면 됩니다.
    }
}

*(플레이어와 상호작용, 충돌반응 => 이벤트 디스패쳐를 통해 다른 스크립트로 이벤트 전달) DropItem

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using static UnityEditor.PlayerSettings;

public class DropItem : MonoBehaviour
{
    public enum eDropItemType
    {
        FOOD,
        EQUIPMENT,
        RELIC,
        WEAPON,
    }
    public eDropItemType type;
    bool isFullInvenCount = default;
    public void Init()
    {
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Player"))
        {
            Debug.LogFormat("{0}",this.gameObject.tag);

            switch (this.gameObject.tag)
            {
                case "Equipment":
                    this.type=eDropItemType.EQUIPMENT;       
                    //인벤토리 용량 체크
                                        
                    EventDispatcher.Instance.Dispatch(EventDispatcher.EventName.UIInventoryAddEquipment, GetEquipmentItem(), out isFullInvenCount);
                    Debug.LogFormat("<Color=red>name:{0}</Color>", this.GetEquipmentItem());
                    break;

                case "Food":
                    this.type=eDropItemType.FOOD;
                    this.GetFoodItem();
                    Debug.LogFormat("<Color=red>name:{0}</Color>", this.GetFoodItem());
                    break;
                case "Relic":
                    this.type=eDropItemType.RELIC;
                    this.GetRelicItem();
                    Debug.LogFormat("<Color=red>name:{0}</Color>", this.GetRelicItem());
                    break;
                case "Weapon":
                    this.type = eDropItemType.WEAPON;
                    this.GetWeaponItem();
                    Debug.LogFormat("<Color=red>name:{0}</Color>", this.GetWeaponItem());
                    break;
            }
        }        
    }


    public string GetFoodItem()
    {

        var goSp = this.gameObject.GetComponent<SpriteRenderer>().sprite;
        Destroy(this.gameObject);
        return goSp.ToString();
    }
    public string GetEquipmentItem()
    {
        var goSp = this.gameObject.GetComponent<SpriteRenderer>().sprite;
        if (isFullInvenCount)
        {
            //this.GetEquipmentItem();
            Destroy(this.gameObject);
        }
        else
        {
            Debug.Log("용량 FUll");
        }
        return goSp.ToString();
    }
    public string GetWeaponItem() 
    {
        var goSp = this.gameObject.GetComponent<SpriteRenderer>().sprite;
        Destroy(this.gameObject);
        return goSp.ToString();
    }
    public string GetRelicItem()
    {
        var goSp = this.gameObject.GetComponent<SpriteRenderer>().sprite;
        Destroy(this.gameObject);
        return goSp.ToString();
    }


    private IEnumerator DestroyItem()
    {
        yield return null;
    }
}

 

*인벤토리 용량을 체크한 후 bool 값을 반환하는 메서드이다
*이 메서드를 AddListener 에 담아서 드랍된 아이템 스크립트에서 호출할 예정이다.
* DropItem(드랍된 아이템 스크립트) AddListener에서 담아온 메서드 AddEquipment를 Dispatch로 호출한다. DropItem 스크립트에서 정의한 메서드인 GetEquipmentItem은 해당 오브잭트의 sprite를 string으로 받아서 반환한다.

 

# 혼자 만드는 과정과는 완전 다른 느낌이었다. 서로의 스크립트 간에 상호작용을 완벽하게 이해할 필요가 있었다.

다행히 이벤트 디스패쳐라는 기능을 만들어 놔서 아주 편하게 이벤트를 주고 받고있다. 다만 어떤 상호작용이 어떤 과정으로 이루어지는지, 어느시점에서 이루어지는지 이런 상황들을 파악하는데에 오래걸렸다. 좀더 게임 프로세스에 대해 많은 사고가 필요하겠다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함