检查是否按下了UI按钮或Unity选项

时间:2017-12-18 11:32:16

标签: c# unity3d

我需要一种方法来检查是否按下了一个UI按钮点击事件并不是真的有用,因为输入法(称为蚀刻时间,玩家的回合)必须将值返回主函数,而循环将完全停止游戏并且输入应该只在玩家转动时被接受(当玩家转动方法等待输入时),由于这些原因,Unity事件触发器似乎不是一个可用的选项。我需要的是一种方式检查按钮的状态。

注意:我使用对象的Start()方法作为我的Main方法 如果有任何问题,请告诉我

另请注意:我正在将游戏转移到Unity,因此我希望在对代码进行最少更改的情况下更改输入+输出方法

 //TurnInput is an array of bools tracking witch buttons are being pressed 
 //(9 buttons)
 private  Block[] PlayerTurn(Block[] grid )
{
    TurnNotDone = false;
    while (!TurnNotDone)
    {
        //gets stuck unity crash
        //needs to wait until player click on one of the buttons
        //(when player click on a button is turn is over and the turn is 
        //passed to the AI)
    }
    for (int i = 0; i < 9; i++)
    {
        if (TurnInput[i]) grid[i] = SetBlock("O");
    }
    return grid;
}
//trigger by event trigger on button gets an int for the button Index
public void PointerDown (int i)
{
    TurnInput[i] = true;

}
//trigger by event trigger on button gets an int for the button Index
public void PointerUp(int i)
{
    TurnInput[i] = false;
}

1 个答案:

答案 0 :(得分:3)

也许您可以使用协程而不是while循环:

  1. gameloop coroutine“停止”在玩家转动为真时等待用户输入
  2. ButtonClicked事件处理set playerTurn为false(将ButtonClicked方法添加到UI按钮的OnClick事件处理程序)
  3. AI轮到
  4. 将playerTurn再次设置为true
  5. 转到1
  6. 最小例子:

    public class MinimalExample : MonoBehaviour {
    
    public struct Block {
        public bool isOBlock;
    }
    
    bool playerTurn;
    Block[] grid;
    bool[] TurnInput;
    
    // Use this for initialization
    void Start () {
        grid = new Block[9];
        TurnInput = new bool[9];
        StartCoroutine (GameLoop());
    }
    
    // GameLoop
    IEnumerator GameLoop () {
        while (true) {
            yield return new WaitWhile (() => playerTurn == true);
            for (int i = 0; i < 9; i++) {
                if (TurnInput[i]) grid[i] = SetBlock("O");
            }
            Debug.Log ("AI here");
            playerTurn = true;
        }
    }
    
    Block SetBlock(string s) {
        var r = new Block ();
        r.isOBlock = (s == "O");
        return r;
    }
    
    //trigger by event trigger on button gets an int for the button Index
    public void ButtonClicked (int i) {
        TurnInput[i] = true;
        playerTurn = false;
    }
    
    }