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

相关推荐
小拉达不是臭老鼠10 小时前
Unity学习_ScriptableObject
学习·unity
Thomas_YXQ11 小时前
Unity无GC读取图片与网格完整方案
大数据·人工智能·unity·微信·产品运营
summerkissyou198713 小时前
Android-UI-获取屏幕尺寸的方法
android·ui
jiayong2314 小时前
虚幻引擎 Unreal Engine 通俗指南
游戏引擎·虚幻
郝学胜-神的一滴15 小时前
中级OpenGL教程 008:精准控制高光光斑大小与强度
c++·unity·godot·three.js·图形学·opengl·unreal
avi911117 小时前
Unity 商业插件之(五)课外2 - Zenject的一些小Tips(学习备忘)
unity·游戏开发·团结引擎
汉得数字平台18 小时前
让提示更智能,弹窗更灵动:Choerodon UI 浮层交互体验优化
ui·前端组件
元气少女小圆丶18 小时前
SenseGlove Nova 2+Unity开发笔记4
笔记·unity·游戏引擎
basketball61619 小时前
Go 语言从入门到进阶:6. 一文彻底吃透结构体(Struct)
开发语言·unity·golang
aaaffaewrerewrwer19 小时前
一个更流畅、更纯粹的在线 2048 游戏(浏览器即开 / 无需下载)
游戏·2048