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

相关推荐
图扑可视化2 小时前
统一 DataModel 底座,HT UI 组件万物同源|中篇・运笔
ui·数字孪生·组件
qq_369224337 小时前
ddraw.dll丢失是什么原因引起的?老游戏运行报错,多种可行修复手段汇总分享
windows·游戏·dll·dll修复·dll丢失·dll错误
xiaohe06018 小时前
🎮 豆包完胜 DeepSeek ?!零玩家竞技场,AI Agent 专属对弈!
游戏·llm·agent
微三云生态系统架构师-彭丹11 小时前
任务卷轴积分系统架构设计:从任务状态机到合规风控的完整实现
unity·系统架构·游戏引擎
XR技术研习社12 小时前
从 PICO 文档看未来短期内的 Unity 版本选择
unity·游戏引擎·xr·vr
星栈独行13 小时前
自定义 UI-UX-Pro-Max 的 CSV 知识库,把 AI 生成的后台拉回行业该有的样子
前端·人工智能·ui·ux
白搞电子13 小时前
ESP-Mosaico 掌上游戏开发:LVGL 抛硬币动画、音频混音与 BMI270 摇晃触发
单片机·嵌入式硬件·物联网·游戏·音视频
开开心心就好15 小时前
手机悬屏翻译工具外语游戏漫画APP全覆盖
android·前端·javascript·python·游戏·pdf·html
河南花仙子科技15 小时前
如何通过小游戏后台数据优化运营策略
科技·游戏
玖玥拾15 小时前
Unity 热更新(一)
unity·游戏引擎