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

相关推荐
派葛穆1 小时前
Unity-UI 输入框功能
ui·unity·游戏引擎
玖玥拾1 小时前
Unity3D RPG 入门项目(一)开场动画/人物移动/摄像机跟随场景切换
unity·游戏引擎
2401_894915533 小时前
GEO 搜索优化完整源码从零部署:环境配置、集群搭建全流程
开发语言·python·tcp/ip·算法·unity
2501_936415693 小时前
可变参数&综合练习&斗地主游戏
java·windows·游戏
WarPigs4 小时前
PC端加载安卓AB包资源显示紫色的问题
unity
笨鸟先飞的橘猫6 小时前
只会脚本语言的游戏后端自我提升之路——c++学习(开篇)
学习·游戏
scott.cgi7 小时前
Unity使用AndroidX获取,导航栏与虚拟键盘的高度
unity·androidx·keyboard·导航栏高度·虚拟键盘高度·判断键盘关闭·获取虚拟键盘高度
丁小未8 小时前
Unity车机地图Tile流式渲染系统高性能架构方案
unity·架构·ecs·dots·车机系统·车机系统架构图
笨鸟先飞的橘猫8 小时前
游戏后端分布式学习——消息队列在游戏的用法
分布式·学习·游戏
网站优化(SEO)专家10 小时前
Pokicon免费游戏入口网站流量稳定增长的核心密码
游戏·游戏网站·网站流量·游戏宣传