Unity游戏冻结

时间:2017-10-18 12:01:13

标签: c# unity3d freeze

我有这个代码,但是当我尝试运行它时,Unity Freezes,我有一个无法看到的无限循环吗?

using UnityEngine;

using UnityEngine.UI;

using UnityEngine.SceneManagement;

using System.Collections;

using System.Collections.Generic;

public class GameManager : MonoBehaviour {

    public Sprite[] cardFace;
    public Sprite cardBack;
    public GameObject[] cards;
    public Text matchText;

    private bool _init = false;
    private int _matches = 13; 
    public int i;

    // Update is called once per frame
    void Update () {  //basically what it does is it doesn't hit the update until everything is loaded
        if (!_init)
            initializeCards ();
        if (Input.GetMouseButtonUp(0)) //player has left clicked
        checkCards();
    }


    void initializeCards()
    {
        for (int id = 0; id <2; id++)
        {
            for (i = 1; i < 14; i++)
            {

                bool test = false;
                int choice = 0; 
                while (!test)
                {
                    choice = Random.Range(0, cards.Length);
                    test = !(cards [choice].GetComponent<card>().initialized);
                }
                cards[choice].GetComponent<card>().cardValue = i;
                cards[choice].GetComponent<card>().initialized = true;
            }
        }

        foreach (GameObject c in cards)
            c.GetComponent<card>().setupGraphics();

        if (!_init)
            _init = true;
    }



    public Sprite getCardBack()
    {
        return cardBack;
    }

    public Sprite getCardFace()
    {
        return cardFace[i - 1];
    }

    void checkCards()
    {
        List<int> c = new List<int>();

        for (i = 0; i < cards.Length; i++)
        {
            if (cards[i].GetComponent<card>().state == 1)
                c.Add(i);
        }

        if (c.Count == 2)
            cardComparison(c);
    }

    void cardComparison(List<int> c)
    {
        card.DO_NOT = true;

        int x = 0;

        if (cards[c[0]].GetComponent<card>().cardValue == cards[c[1]].GetComponent<card>().cardValue)
        {
            x = 2;
            _matches--;
            matchText.text = "Number of Matches: " + _matches;
            if (_matches == 0)
                SceneManager.LoadScene("bedroomscene");
        }

        for (int i = 0; i < c.Count; i++){
            cards[c[i]].GetComponent<card>().state = x;
            cards[c[i]].GetComponent<card>().falseCheck();
        }
    }
}

我有可能犯了一个非常愚蠢的错误,但请帮助我找到导致团结冻结的原因。

1 个答案:

答案 0 :(得分:1)

对于阵列的至少一个组件,您确定已初始化 错误吗?
否则,它不会从这个循环中断:
此外,因为选择的值是随机的。它也不确定它是否会打破while循环。

while (!test)
{
     choice = Random.Range(0, cards.Length);
     test = !(cards [choice].GetComponent<card>().initialized);
}