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、运行程序

相关推荐
Getflare2 小时前
前端 + UI 设计 + AI:这不是三个工种,是一个新三角能力模型(附自检清单)
前端·人工智能·ui
noipp3 小时前
推荐题目:洛谷 P6231 [JSOI2013] 公交系统
c语言·数据结构·c++·算法·游戏·洛谷·luogu
达子6664 小时前
第9章_HarmonyOs图解 用Java开发UI
java·ui·harmonyos
金銀銅鐵8 小时前
[Python] 用 turtle 来绘制国际象棋棋盘(不含棋子)
python·游戏
<小智>10 小时前
鸿蒙多功能工具箱开发实战(二十四)-单元测试与自动化测试
ui·华为·harmonyos
Python私教11 小时前
Godot怎么下载和安装?零基础完成第一次启动
人工智能·游戏·godot
电子云与长程纠缠12 小时前
UE中使用TGuardValue与TInlineComponentArray数据结构
开发语言·数据结构·学习·ue5·游戏引擎
玖玥拾12 小时前
Unity 3D 笔记(十二)Unity/C# Socket 网络笔记1
网络·unity·c#
玖玥拾13 小时前
Unity 3D 笔记(十五)Unity/C# Socket 网络笔记4
服务器·网络·unity·c#
早点睡啊Y15 小时前
深入学LangChain官方文档(二十二):Frontend 高级形态——Headless Tools、Time Travel 与 Generative UI
ui·langchain·状态模式