选择用户界面项,然后执行某项操作

时间:2019-05-17 04:23:02

标签: c# unity3d

我正在为我的游戏开发一个小型市场系统。我正在尝试选择商品,然后可以购买。我设法弄清楚了什么时候选择了物品,如果是的话,我启动了一个使其能够购买的功能。但是,由于我只能在选中某项后才能购买,因此当我按下“购买”按钮时,它将取消选择。为什么会这样,但我将如何解决呢?

请查看我的代码以查看我尝试过的内容。

关于选择的项目脚本:

public void OnSelect(BaseEventData eventData){

        // do stuff when selected
        itemSelected = true;

    }

public void OnDeselect(BaseEventData eventData){

    // do stuff when deselected
    itemSelected = false;

}

按钮的onClick事件(市场脚本):

public void purchaseItem(){

    if (item [1].itemSelected) {

        // subtract price of the item from the balance
        pointsManager.gameCash -= item[1].itemPrice;

    }

    if (item [2].itemSelected) {

        // subtract price of the item from the balance
        pointsManager.gameCash -= item[2].itemPrice;

    }

    if (item [3].itemSelected) {

        // subtract price of the item from the balance
        pointsManager.gameCash -= item[3].itemPrice;

    }

    if (item [4].itemSelected) {

        // subtract price of the item from the balance
        pointsManager.gameCash -= item[4].itemPrice;

    }

我想要做的就是选择一个按钮(项目),然后通过onClick事件购买它。

1 个答案:

答案 0 :(得分:0)

此处的问题:通过单击按钮,Unity会自动在所有其他UI元素上触发OnDeselect。你真的无法解决这个问题。


我宁愿自己使用IPointerClickHandler接口之类的东西来实现它

public class YourSelectableClass : MonoBehaviour, IPointerClickHandler
{
    public bool itemSelected;

    public void Deselect()
    {
        itemSelected = false;
    }

    public override void OnPointerClick(PointerEventData pointerEventData)
    {
        // Deselect all others
        // Note that this only deselects currently active and enabled
       // ones. Later you might rather use a manager class and register them all
       // in order to also look for them only once
        foreach(var selectable in FindObjectsOfType<YourSelectableClass>())
        {
            selectable.Deselect();
        }

        itemSelected = true;
    }    
}

然后您可以像使用Linq FirstOrDefault那样简化按钮方法

using System.Linq;

...

public void purchaseItem()
{
    var selectedItem = item.FirstOrDefault(i => i.itemSelected);

    // Nothing was selected => do nothing
    if(!selectedItem) return;

    // subtract price of the item from the balance
    pointsManager.gameCash -= selectedItem.itemPrice;

    ...
}

i => i.itemSelected是一个lambda表达式,其中i用作迭代器。基本上与

相同
foreach(var i in item)
{
    if(i.itemSelected) return i;
}

return null;

注意:在智能手机上键入内容,因此没有保修,但我希望这个主意会清楚