1
我有這段代碼,但是當我嘗試運行它時Unity凍結,我有無限循環,我看不到?Unity遊戲凍結
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();
}
}
}
有一個機會,我做了一個非常愚蠢的錯誤,但請幫我找到導致團結凍結的原因。
可能是因爲while循環。 – Thalthanas
一般來說,試圖生成所有卡片的列表,然後「隨機選擇一個」是一個非常糟糕的主意。一個更好的方法是先生成一副牌然後隨機分類一次,然後依次抽出牌。或者,創建一個包含所有卡片的卡組,隨機選擇一張卡片,並將其從卡組中移除,以便下一個隨機選擇的卡片可供選擇。 – PMV