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 小时前
基于SpringBoot的游戏攻略社区交流系统-附源码
spring boot·后端·游戏
一只大鸽子4 小时前
游戏开发笔记7-Godot RPG游戏基础-场景切换、全局脚本
笔记·游戏·godot
赤生云电竞7 小时前
云游戏边缘节点部署实践:机房选址与网络拓扑选型
网络·游戏·php
芝麻粒儿8 小时前
Scratch少儿编程案例-鼠标控制练习
游戏·青少年编程·计算机外设·scratch·少儿编程
科技小登8 小时前
DDoS防护选型测评:高防CDN、高防IP与SDK游戏盾怎么做同口径POC?
tcp/ip·游戏·ddos
zdr尽职尽责1 天前
UnityCli 兼容2022版本
ui·unity·ai·c#·游戏引擎
xx z1 天前
打开游戏提示 d3dx9_43.dll 缺失怎么办(DirectX 修复步骤)
windows·游戏·工具·软件
珍猪吃饲料2 天前
消息丢了、重复消费了,MQ 这套账该怎么算
游戏
芝麻粒儿2 天前
Scratch少儿编程案例-多人联机与IO游戏(1)
游戏·青少年编程·scratch·少儿编程
辰小忆2 天前
11 · RunCurveChart —— 实时运行曲线
c++·ui·duilib