【发布时间】:2022-08-15 04:08:50
【问题描述】:
请告诉我。我有 2 个脚本挂在不同的 Unity 对象上。第一个脚本用于单击按钮。第二个用于执行功能。 如果按下按钮,如何执行 AddItem 函数?
脚本 1(按钮单击):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class UseButton : MonoBehaviour, IPointerUpHandler, IPointerDownHandler
{
public bool isClick = false;
public void OnPointerDown(PointerEventData ped)
{
isClick = true;
}
public void OnPointerUp(PointerEventData ped)
{
isClick = false;
}
}
脚本 2(添加项目):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class InventoryManager : MonoBehaviour
{
public void AddItem(ItemScriptableObject _item, int _amount)
{
foreach(InventorySlot slot in slots)
{
if (slot.item == _item)
{
slot.amount += _amount;
return;
}
}
foreach(InventorySlot slot in slots)
{
//print(_item+\" \"+_amount);
if (slot.isEmpty == true)
{
slot.item = _item;
slot.amount = _amount;
slot.isEmpty = false;
slot.SetIcon(_item.icon);
return;
}
}
}
-
可以说,更好的方法之一是让您的 isclick 成为一个属性并拥有一个事情可以订阅的事件。然后,您可以安全地做任何您喜欢 onclick 的事情。
-
@BugFinder 你能举个例子吗?
-
我不是想在手机上打出一个完整的例子。谷歌属性和事件。