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 小时前
制作一款打飞机游戏26:精灵编辑器
游戏·编辑器
SlowFeather2 小时前
Unity 使用 ADB 实时查看手机运行性能
android·unity·adb·性能优化·profiler
AiFlutter6 小时前
低代码平台开发手机USB-HID调试助手
单片机·游戏·计算机外设
工藤新一¹8 小时前
C++/SDL进阶游戏开发 —— 双人塔防游戏(代号:村庄保卫战 13)
c++·游戏·游戏引擎·毕业设计·sdl·c++游戏开发·渲染库
虾球xz9 小时前
游戏引擎学习第247天:简化DEBUG_VALUE
c++·学习·游戏引擎
小赖同学啊12 小时前
Unity 和 Unreal Engine(UE) 两大主流游戏引擎的核心使用方法
unity·游戏引擎·虚幻
工藤新一¹13 小时前
C++/SDL 进阶游戏开发 —— 双人塔防(代号:村庄保卫战 14)
开发语言·c++·游戏引擎·游戏开发·sdl·实践项目
AgilityBaby13 小时前
unity Animation学习,精准控制模型动画播放
学习·3d·unity·游戏引擎