0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

FarmRPG Unity Inventory&Item Part2 2/2 InventoryManager playerがItemに接触したときの処理を実装 Collider2D OnTriggerEnter2D

Posted at

概要

今回はplayerがItemに接触した時にログを出す処理を追加します。

以下gif画像は実装後の画像です。

ffffffffffffdsafdasnjlkljllkklll.gif

開発環境

IDE:Rider
Unity:2020.3.42(LTS)
OS:Windows10

UnityEditor上の設定

Playerオブジェクト

Is TriggerをOFFにします。
image.png

Itemオブジェクト

ItemObjectにBoxColliderコンポーネントを追加されていることを確認します。
Is TriggerをONにします。
image.png

実装のポイント

PlayerとItemが接触したときの流れ

image.png

コード部分

ItemPickUp

ItemPickUp.cs
using System;
using UnityEngine;


public class ItemPickUp : MonoBehaviour
{
    private void OnTriggerEnter2D(Collider2D collsion)
    {
        Item item = collsion.GetComponent<Item>();
        if (item != null)
        {
            ItemDetails itemDetails = InventoryManager.Instance.GetItemDetails(item.ItemCode);
            Debug.Log(itemDetails.itemDescription);
        }
    }
}

InventoryManager

InventoryManager.cs
using System.Collections.Generic;
using UnityEngine;


public class InventoryManager : SingletonMonobehaviour<InventoryManager>
{
    private Dictionary<int, ItemDetails> itemDetailDictionary;
    [SerializeField] private SO_ItemList itemList = null;

    private void Start()
    {
        CreateItemDetailsDictionary();
    }

    private void CreateItemDetailsDictionary()
    {
        itemDetailDictionary = new Dictionary<int, ItemDetails>();

        foreach (ItemDetails itemDetails in itemList.itemDetails)
        {
            itemDetailDictionary.Add(itemDetails.itemCode,itemDetails);
        }
    }

+    public ItemDetails GetItemDetails(int itemCode)
+    {
+        ItemDetails itemDetails;
+        if (itemDetailDictionary.TryGetValue(itemCode, out itemDetails))
+        {
+            return itemDetails;
+        }
+        else
+        {
+            return null;
+        }
+    }
}


参考

C#

Dictionary.TryGetValue(TKey, TValue)

image.png

Unity Editor コンポーネント

image.png

Unity スクリプト

OnTriggerEnter2D

image.png

その他

Section7 22 InventoryManager Class

github コミット分(個人確認用 privateなので見れません)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?