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

相关推荐
FairGuard手游加固3 分钟前
2026年7月份国产游戏审批信息
游戏
星空露珠6 小时前
28种颜色对应名称,
开发语言·数据库·算法·游戏·lua
中国搜索直付通7 小时前
棋牌游戏支付与防沉迷:二级商户如何构建“免疫系统”
游戏
2601_962924767 小时前
遗忘之海手游战术家怎么玩 遗忘之海手游战术家玩法攻略
游戏
<小智>8 小时前
鸿蒙多功能工具箱开发实战(二十)-性能优化与打包发布
ui·华为·harmonyos
雅客李8 小时前
2026年第三季度云手机实测 游戏多开挂机托管三维度数据公开
游戏·智能手机
xcLeigh11 小时前
Unity基础:创建你的第一个游戏物体——Cube、Sphere与基本3D物体
游戏·3d·unity·教程
ellis197011 小时前
C#异常相关关键字:Exceptions,throw,try,catch,finally
unity·c#
_Tenk_11 小时前
自研开源小工具 SwitchDeck:一键切换分辨率/刷新率/音频输出(附 WinForms 高 DPI 踩坑实录)
游戏·分辨率·cs2·看电影·一键切换·音响耳机音频·州瓦go
薛定谔的猫-菜鸟程序员13 小时前
一个 Skill 如何让大模型拥有专业 UI 能力?——ui-ux-pro-max 架构深度拆解与 Skill 设计方法论
人工智能·ui