库存模块主要参考了 youtube 上的视频
BMo 的 Flexible INVENTORY SYSTEM in Unity with Events and Scriptable Objects 和 Simple Inventory UI in Unity With Grid Layouts 这两个视频是一个系列
还是一个视频也是 BMo的 How To INTERACT with Game Objects using UNITY EVENTS Tutorial
这三个视频讲述了怎么用Unity Event、delegate、Collider Trigger 的功能去做一个库存系统。
但我感觉 delegate 代理类注册的写法需要在另外一个类中硬编码会比较不美观,所有换了一种两个事件调用的写法。
功能点主要有两个:一个是物品从地图进入到库存,另一个就是,反过来,物品从库存中消失。
总体来说,前者比较复杂,后者比较简单。后者的功能代码仅仅是前者的一部分。
物品从地图进入到库存中的过程有三个:人物进到物品可以交互的范围里、人物和物品交互、物品进入到人物的库存中。这三个流程可以分别设计成独立的实体。
人物进到物品可以交互的范围里
人物可以交互的范围是有限的,不然就会出现人物隔着很远的距离可以和N多个物品交互。
这块功能的实现主要是用了 Unity Collider 2D 的功能,Collider 2D不仅可以作为实体碰撞的功能,也能检测物体从范围外进入到范围内。通过在 C# 中实现 OnTriggerEnter2D 和 OnTriggerExit2D 方法,就可以达到检测人物是否进入到物品可以交互的范围里。
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class PickUpControl : MonoBehaviour
{
public Boolean isInRange;
public KeyCode interactKey;
public UnityEvent interactEvent;
void Update()
{
if(isInRange)
{
if(Input.GetKeyDown(interactKey))
{
interactEvent.Invoke();
UnityEngine.Debug.Log($"{transform.parent.name} Interact Event invoke");
}
}
}
/// <summary>
/// Sent when another object enters a trigger collider attached to this
/// object (2D physics only).
/// </summary>
/// <param name="other">The other Collider2D involved in this collision.</param>
void OnTriggerEnter2D(Collider2D other)
{
if(other.transform.CompareTag("Player"))
{
isInRange = true;
UnityEngine.Debug.Log($"{transform.parent.name} is in range");
}
}
/// <summary>
/// Sent when another object leaves a trigger collider attached to
/// this object (2D physics only).
/// </summary>
/// <param name="other">The other Collider2D involved in this collision.</param>
void OnTriggerExit2D(Collider2D other)
{
if(other.transform.CompareTag("Player"))
{
isInRange = false;