Unity3D仿星露谷物语开发34之单击Drop项目

1、目标

当在道具栏中选中一个Item时,点击地面就可以实现Item的drop操作,每点击一次就drop一次,直到道具栏中Item数量不够。

这样的好处:避免每次Drop都从道具栏中拖拉Item,通过点击这种操作可以更加高效。

方法:通过EventHandler脚本创建Event,在Player脚本中处理点击并触发Event,在UIInvenrotySlot脚本中订阅Event进行处理。

2、优化EventHandler脚本

添加如下事件代码:

3、优化Player脚本

添加如下变量:

cs 复制代码
private GridCursor gridCursor;

添加Start方法:

cs 复制代码
private void Start()
{
    gridCursor = FindObjectOfType<GridCursor>();
}

在Update中添加如下代码:

其具体实现如下:

cs 复制代码
private void PlayerClickInput()
{
    if (Input.GetMouseButton(0))
    {
        if (gridCursor.CursorIsEnabled)
        {
            ProcessPlayerClickInput();
        }
    }
}

相关的代码实现如下:

cs 复制代码
 private void ProcessPlayerClickInput()
 {
     ResetMovement();

     // Get Selected item details
     ItemDetails itemDetails = InventoryManager.Instance.GetSelectedInventoryItemDetails(InventoryLocation.player);

     if(itemDetails != null)
     {
         switch (itemDetails.itemType)
         {
             case ItemType.Seed:
                 if (Input.GetMouseButtonDown(0))
                 {
                     ProcessPlayerClickInputSeed(itemDetails);
                 }
                 break;
             case ItemType.Commodity:
                 if (Input.GetMouseButtonDown(0))
                 {
                     ProcessPlayerClickInputCommodity(itemDetails);
                 }
                 break;
             case ItemType.none:
                 break;
             case ItemType.count:
                 break;

             default:
                 break;
         }
     }
 }

 private void ProcessPlayerClickInputSeed(ItemDetails itemDetails)
 {
     if(itemDetails.canBeDropped && gridCursor.CursorPositionIsValid)
     {
         EventHandler.CallDropSelectedItemEvent();
     }
 }

 private void ProcessPlayerClickInputCommodity(ItemDetails itemDetails)
 {
     if(itemDetails.canBeDropped && gridCursor.CursorPositionIsValid)
     {
         EventHandler.CallDropSelectedItemEvent();
     }
 }

4、优化UIInventorySlot脚本

在OnEnable方法中增加如下代码,订阅事件并进行处理。

5、运行程序

相关推荐
ZC跨境爬虫32 分钟前
模块化烹饪小程序开发日记 Day7:(菜谱详情接口开发与JSON数据读取全流程)
前端·javascript·css·ui·微信小程序·json
魔法阵维护师5 小时前
从零开发游戏需要学习的c#模块,第二十四章(瓦片地图 —— 让世界有墙)
学习·游戏·c#
王翼鹏7 小时前
claude code 使用ui-spec 命令生成UI设计说明
ui·自定义命令·claude code
人还是要有梦想的7 小时前
QT数据库乱码、QT qml import导入库报错、ui界面分层设计
开发语言·qt·ui
小许同学记录成长9 小时前
QGC地面站 UI 界面开发
qt·ui·架构
程序员JerrySUN9 小时前
Jetson边缘嵌入式实战课程第五讲:Jetson Secure Boot - 安全启动
android·linux·服务器·人工智能·安全·unity·游戏引擎
Zik----10 小时前
Unity 虚拟美术馆漫游系统
unity·vr·虚拟现实
华玥作者10 小时前
从“碎片化”到“资产化”:Vue3 + UniApp 组件库的进化论
ui·uni-app·vue·组件库
tkokof110 小时前
捉虫(Bug)再记
游戏·bug·游戏开发
孬甭_11 小时前
贪吃蛇游戏 模拟实现
c语言·游戏