所以我尝试使用while循环让我的程序找到通过8x8数组的路径。但是,在启动时Unity会停止响应并且必须关闭。有人可以帮助解释为什么我的代码不起作用,因为我没有看到任何错误,因为循环结束的条件发生了变化。这是源代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelGenerator : MonoBehaviour {
public int counter = 0;
int LevelX = 0;
int LevelY = 0;
int[,] LevelData = new int[8,8]{
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0}
};
void Start () {
Generate();
}
void RandomPath(){
int NewDirection = Random.Range(0,3);
if(NewDirection==0){
if(LevelX!=0){
if(LevelData[LevelX-1,LevelY]==0){
counter++;
LevelData[LevelX-1,LevelY]=counter;
LevelX=LevelX-1;
}
}
}else if(NewDirection==1){
if(LevelX!=7){
if(LevelData[LevelX+1,LevelY]==0){
counter++;
LevelData[LevelX+1,LevelY]=counter;
LevelX=LevelX+1;
}
}
}
else if(NewDirection==2){
if(LevelY!=7){
if(LevelY!=0){
if(LevelData[LevelX,LevelY-1]==0){
counter++;
LevelData[LevelX,LevelY+1]=counter;
LevelY=LevelY+1;
}
}else{
counter++;
LevelData[LevelX,LevelY+1]=counter;
LevelY=LevelY+1;
}
}
}
}
void Generate(){
//picks a random location for the level to start and the second room, then generates a random path to the bottom of the level
int LevelStartX = Random.Range(0,8);
int LevelStartY = Random.Range(0,5);
counter++;
LevelData[LevelStartX,LevelStartY] = counter;
Debug.Log(LevelStartX);
Debug.Log(LevelStartY);
int Direction = Random.Range(0,3);
if(Direction==0){
if(LevelStartX==0){
counter++;
LevelData[LevelStartX+1,LevelStartY]=counter;
LevelX = LevelStartX+1;
LevelY = LevelStartY;
}else{
counter++;
LevelData[LevelStartX-1,LevelStartY]=counter;
LevelX = LevelStartX-1;
LevelY = LevelStartY;
}
}else if(Direction==1){
if(LevelStartX==7){
counter++;
LevelData[LevelStartX-1,LevelStartY]=counter;
LevelX = LevelStartX-1;
LevelY = LevelStartY;
}else{
counter++;
LevelData[LevelStartX+1,LevelStartY]=counter;
LevelX = LevelStartX+1;
LevelY = LevelStartY;
}
}else{
counter++;
LevelData[LevelStartX,LevelStartY+1]=counter;
LevelX = LevelStartX;
LevelY = LevelStartY+1;
}
while(LevelY!=7 || counter!=32){
RandomPath();
}
}
}
答案 0 :(得分:0)
我检查了你的代码,发现计数器永远不会达到32(或至少通常)。这可能是因为你使用的是随机数字,每次运行时都会以不同的数字停止,因此实际工作的可能性很小