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

相关推荐
鹤卿1235 小时前
OC UI ——UIGestureRecognizer 手势识别
ui·ios·objective-c
运筹vivo@5 小时前
leetcode每日一题: 跳跃游戏 IV
leetcode·游戏·宽度优先
为你写首诗ge6 小时前
【Unity知识分享】Mirror实现房间等待功能(创建房间 / 搜索房间、加入房间、房间准备、房间内角色设置、返回房间)
unity·mirror·房间等待功能
阿正的梦工坊6 小时前
React:构建用户界面的JavaScript库
javascript·react.js·ui
游乐码6 小时前
Unity坦克案例疑难记录(二)
unity·游戏引擎
小白学鸿蒙7 小时前
Funplay Unity MCP 接入 trae 实战
unity·游戏引擎·mcp
ZC跨境爬虫8 小时前
跟着 MDN 学 HTML day_62:(HTML调试与常见错误修复指南)
java·前端·javascript·ui·html·媒体
sheeta19988 小时前
LeetCode 每日一题笔记 日期:2026.05.18 题目:1345. 跳跃游戏 IV
笔记·leetcode·游戏
赏金术士8 小时前
第二章:Compose入门—声明式UI编程
android·ui·kotlin·compose
德迅云安全-小潘9 小时前
游戏行业面临的网络安全挑战
安全·web安全·游戏