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

相关推荐
警醒与鞭策5 小时前
Codex桌面版与Claude桌面版使用设置
android·unity·ai·性能优化
装备研究社6 小时前
对峙2掉线排查实测
游戏
xcLeigh6 小时前
Unity基础:Destroy与DestroyImmediate——正确销毁游戏物体的方式
游戏·unity·游戏引擎·教程
sunxfancy7 小时前
EVEngine 0.6 到 0.6.1:让 AI 参与游戏开发,还需要补上哪些环节?
游戏
sunxfancy8 小时前
AI 改完场景,怎么知道没改坏?EVEngine 0.6.1 的白盒自动试玩
游戏
风无雨10 小时前
三角洲如何快速拾取物品
游戏
lllhhh_远方12 小时前
unity中URP场景阴影锯齿严重解决方案
unity·游戏引擎
老王的笔记v13 小时前
71期 免费开源游戏资源管理工具 Pavise模式切换 游戏库 程序白名单与系统体检
游戏·电脑
淡海水15 小时前
07-06-源码-.NET Core GC的极致优化技术
unity·架构·c#·.netcore·gc·1024程序员节
野区捕龙为宠15 小时前
Unity 中使用 UnityWebRequest 加载 StreamingAssets 文件夹中的图片
unity·游戏引擎