首页 > 解决方案 > 在 Unity 中为按钮数组中的每个按钮分配整数值

问题描述

有没有办法根据按钮文本为数组中的每个 UI 按钮分配一个整数值,然后根据分配的值检查该值 OnClick() 是否有效移动?

基本上

for (int i = 0; i < buttons.Length; i++)
    {
        buttons[i].interactable = true;
        buttons[i].GetComponent<Image>().sprite = null;
        // some code here to assign an integer value to each button in the 
        // array.  int boardSquareValue; is in a separate script named Value 
        // attached to each button object;


    }

每个 Buttons Text 子对象都将 Button 的值作为文本。如果我可以将它转换为一个可用的 int 也会很棒并且可以消除使用外部脚本?

每个按钮游戏对象都有一个名为 Value 的脚本,其中有一个名为 boardSquareValue 的 public in 变量。

有点像tictactoe,只有每个方格都有一个值,有效移动的条件将基于更大板上的这些整数值。

我已经尝试了我能想到的一切。

总而言之,我想点击一个正方形,激活一块(完成),检查该正方形的值,如果值正确(从 0 到 4 的整数值)说是,这一步是有效,或否 此移动无效。我只是无法获得分配给该死按钮的值。

编辑:

显示的每个数字都是正方形的值。玩家不能将棋子放置在价值低于其前一个方格值的方格中。我必须以某种方式将该值分配为 int 。for 循环使按钮可交互并将玩家片段精灵设置为空。如果可能的话,我还需要它来设置每个正方形的整数值。

游戏板和层次结构

脚本:

public void GameSetup()
{
    whosTurnIsIt = 0;
    turnCount = 0;
    turnIcons[0].SetActive(true);
    turnIcons[1].SetActive(false);
    for (int i = 0; i < playAreaSquares.Length; i++)
    {
        playAreaSquares[i].interactable = true;
        playAreaSquares[i].GetComponent<Image>().sprite = null;
        boardSquareValue = playAreaSquares[i].GetComponent<Value>().boardSquareValue;
        Debug.Log(playAreaSquares[i].GetComponent<Value>().boardSquareValue);
    }








}

public void SetValueOfSquare()
{
    //Debug.Log("This square's value is: " + squareValue);
    //squareValue = gameObject.GetComponent<Value>().boardSquareValue;

}

public void PlaySquareButton(int WhichNumber)
 {
    playAreaSquares[WhichNumber].image.sprite = playIcons[whosTurnIsIt];
    playAreaSquares[WhichNumber].interactable = false;
    // int.TryParse(playAreaSquares[WhichNumber]., out boardSquareValueOther.boardSquareValue);
    boardSquareValue = playAreaSquares[WhichNumber].GetComponent<Value>().boardSquareValue;


    if (whosTurnIsIt == 0)
    {
        whosTurnIsIt = 1;
        turnIcons[0].SetActive(false);
        turnIcons[1].SetActive(true);
        Debug.Log(boardSquareValue);
        lastPlayedSquareValueX = boardSquareValue;

    }
    else
    {
        whosTurnIsIt = 0;
        turnIcons[0].SetActive(true);
        turnIcons[1].SetActive(false);
        Debug.Log(boardSquareValueOther.boardSquareValue);
        lastPlayedSquareValueO = boardSquareValue;
    }

 }

}

它现在一团糟,因为我正在尝试很多不同的东西来完成这项工作。

标签: arraysuser-interfacefor-loopunity3dbutton

解决方案


推荐阅读