概要
今回はInventorySlotのアイテムを交換する機能を実装します。
以下実装後の様子です。
開発環境
IDE:Rider
Unity:2020.3.42(LTS)
OS:Windows10
UnityEditor上の設定
なし
実装のポイント
InventoryManagerクラスに新規メソッドSwapInventoryItemを加えます。
SwapInventoryItemではinventoryList[0]の交換元と交換先の要素を交換し、UIに反映します。
UIInventorySlotのEndDragメソッドの内容を修正します。
InventoryManagerクラスのSwapInventoryItemを実行するようにします。
toSlotNumber
コード部分
UIInventorySlot
UIInventorySlot.cs
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class UIInventorySlot : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler
{
private Camera mainCamera;
private GameObject draggedItem;
private Transform parentItem;
public Image inventorySlotHighlight;
public Image inventorySlotImage;
public TextMeshProUGUI textMeshProUGUI;
[SerializeField] private UIInventoryBar inventoryBar = null;
public ItemDetails itemDetails;
[SerializeField] private GameObject itemPrefab;
public int itemQuantity;
+ [SerializeField] private int slotNumber = 0;
public void OnEndDrag(PointerEventData eventData)
{
if (draggedItem != null)
{
Destroy(draggedItem);
if (eventData.pointerCurrentRaycast.gameObject != null && eventData.pointerCurrentRaycast.gameObject.GetComponent<UIInventorySlot>() != null)
{
+ int toSlotNumber = eventData.pointerCurrentRaycast.gameObject.GetComponent<UIInventorySlot>().slotNumber;
+ InventoryManager.Instance.SwapInventoryItem(InventoryLocation.player, slotNumber, toSlotNumber);
}
else
{
if (itemDetails.canBeDropped)
{
DropSelectedItemAtMousePosition();
}
}
Player.Instance.EnablePlayerInput();
}
}
}
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;
public int[] inventoryListCapacityIntArray;
public List<InventoryItem>[] inventoryLists;
public void SwapInventoryItem(InventoryLocation inventoryLocation, int fromItem, int toItem)
{
if(fromItem < inventoryLists[(int)inventoryLocation].Count && toItem < inventoryLists[(int)inventoryLocation].Count && fromItem != toItem && fromItem >= 0 && toItem >= 0 )
{
InventoryItem fromInventoryItem = inventoryLists[(int)inventoryLocation][fromItem];
InventoryItem toInventoryItem = inventoryLists[(int)inventoryLocation][toItem];
inventoryLists[(int)inventoryLocation][fromItem] = toInventoryItem;
inventoryLists[(int)inventoryLocation][toItem] = fromInventoryItem;
EventHandler.CallInventoryUpdatedEvent(inventoryLocation,inventoryLists[(int)inventoryLocation]);
}
}
}
参考
C#
Unity Editor コンポーネント
Unity スクリプト
その他
Section1
github コミット分(個人確認用 privateなので見れません)