我正试图在Unity项目中的随机位置按程序生成恒定数量的建筑。然而,我得到了一个无限循环。
这是我的代码(C#):
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GenerateMap : MonoBehaviour {
public GameObject plane;
public LayerMask unwalkableMask;
Node[,] Map;
public Vector2 gridWorldSize;
GameObject thisBuilding;
public float nodeRadius;
float nodeDiameter;
int gridSizeX, gridSizeY;
int scale;
public int numBuildings = 5;
public int numPrefabs;
public List<Vector3> positions = new List<Vector3> ();
public List<GameObject> buildingPrefabs = new List<GameObject>();
void Awake(){
plane = GameObject.CreatePrimitive(PrimitiveType.Plane);
scale = 15; // scaling the plane gives an 5*scale x 5*scale (x-axis x z-axis) plane, set to 50
plane.transform.localScale = new Vector3 (scale, 1, scale); //scales only in x and z dimensions
}
// Use this for initialization
void Start () {
//GameObject building1 = Resources.Load("Buildings/building1") as GameObject;
//GameObject building2 = (GameObject)Resources.Load ("Buildings/building2");
//GameObject building3 = (GameObject)Resources.Load ("Buildings/building3");
nodeDiameter = nodeRadius*2;
gridSizeX = Mathf.RoundToInt(gridWorldSize.x/nodeDiameter);
gridSizeY = Mathf.RoundToInt(gridWorldSize.y/nodeDiameter);
Generate();
}
//int i = 0;
void Generate(){
for(int i =0; i<numBuildings; i++){
//while(i < numBuildings){
CreateGrid();
List<Node> unwalkables = getUnwalkables();
thisBuilding =(GameObject)InstantiatePrefab(); i++;
CreateGrid();
List<Node> unwalkables2 = getUnwalkables(thisBuilding);
foreach(Node n in unwalkables){
//Debug.Log(n.worldPosition);
bool breaking = false;
foreach(Node m in unwalkables2){
if(n.worldPosition==m.worldPosition){
Destroy(thisBuilding);
i=i-1;
Debug.Log("i after fail " + i);
breaking = true;
break;
}
if(breaking)
break;
}
}
}
}
Object InstantiatePrefab() {
int number = Random.Range (0, numPrefabs);
Vector3 position = new Vector3 (Random.Range (-scale*5, scale*5), 0, Random.Range (-scale*5, scale*5)); //random position in the x,z-plane
positions.Add (position);
position.y = buildingPrefabs [number].transform.position.y; //make sure they spawn on top of the plane instead of y=0 w.r.t. their pivot point
Object building;
if (number != 2) {
building = Instantiate (buildingPrefabs [number], position, Quaternion.Euler (-90f, 0f, 0f));
} else {
building = Instantiate (buildingPrefabs [number], position, Quaternion.identity);
}
return building;
}
void CreateGrid(){
Map = new Node[gridSizeX, gridSizeY];
Vector3 worldBottomLeft = transform.position - Vector3.right * gridWorldSize.x/2 - Vector3.forward * gridWorldSize.y/2;
for(int x=0; x<gridSizeX; x++){
for(int y=0; y<gridSizeX; y++){
Vector3 worldPoint = worldBottomLeft + Vector3.right * (x*nodeDiameter + nodeRadius) + Vector3.forward * (y*nodeDiameter+ nodeRadius);
bool walkable = !(Physics.CheckSphere(worldPoint, nodeRadius, unwalkableMask));
Map[x,y] = new Node(walkable, worldPoint, x, y);
}
}
}
void OnDrawGizmos()
{
Gizmos.DrawWireCube(transform.position, new Vector3(gridWorldSize.x, 1, gridWorldSize.y));
if (Map != null)
{
foreach (Node n in Map)
{
Gizmos.color = (n.walkable)?Color.white:Color.red;
Gizmos.DrawCube(n.worldPosition, new Vector3(nodeDiameter-.1f, nodeDiameter*0.5f, nodeDiameter-.1f));
//Vector3.one * (nodeDiameter-.1f));
}
}
}
List<Node> getUnwalkables(){
List<Node> unwalk = new List<Node>();
foreach(Node n in Map){
if(!n.walkable)
unwalk.Add(n);
}
return unwalk;
}
List<Node> getUnwalkables(GameObject obj){
List<Node> unwalk = new List<Node>();
int borderWidth = 8; //x-dir
int borderHeight = 7; //z-dir
float RightBorder = obj.transform.position.x+nodeRadius+borderWidth*nodeDiameter;
float LeftBorder = obj.transform.position.x-nodeRadius-borderWidth*nodeDiameter;
float TopBorder = obj.transform.position.z+nodeRadius+borderHeight*nodeDiameter;
float DownBorder = obj.transform.position.z-nodeRadius-borderHeight*nodeDiameter;
//Vector3 worldBottomLeft = transform.position - Vector3.right * gridWorldSize.x/2 - Vector3.forward * gridWorldSize.y/2;
foreach(Node n in Map){
if(n.worldPosition.x<RightBorder && n.worldPosition.x>LeftBorder
&& n.worldPosition.z>DownBorder && n.worldPosition.z<TopBorder)
unwalk.Add(n);
}
return unwalk;
}
}
这种方法似乎出了问题:
void Generate(){
for(int i =0; i<numBuildings; i++){
//while(i < numBuildings){
CreateGrid();
List<Node> unwalkables = getUnwalkables();
thisBuilding =(GameObject)InstantiatePrefab(); i++;
CreateGrid();
List<Node> unwalkables2 = getUnwalkables(thisBuilding);
foreach(Node n in unwalkables){
//Debug.Log(n.worldPosition);
bool breaking = false;
foreach(Node m in unwalkables2){
if(n.worldPosition==m.worldPosition){
Destroy(thisBuilding);
i=i-1;
Debug.Log("i after fail " + i);
breaking = true;
break;
}
if(breaking)
break;
}
}
}
}
如果我去掉这条线:I=I-1;我没有得到无限的循环,但我最终会拥有比预期更少的建筑。这一行导致for循环再重复一次迭代,这样它将始终生成至少"numBuildings"数量的建筑。
我在foreach循环中添加了breaking语句,这样,如果条件多次得到满足,"I"就不会一直减少。但这似乎不起作用,只要numBuildings大约为5或更多,就会创建一个无限循环。当这种情况发生时,我不能再退出了,除非强制结束任务。
有人知道我做错了什么吗?或者有没有更好的解决方案来总是建造一些建筑?
如有必要,我随时准备回答有关代码/场景的任何问题。
问题是:Destroy
函数不能立即工作。就我对你的代码的理解而言(我没有深入了解所有细节),一般来说,它的作用是这样的:
- 创建一些建筑
- 找到所有"不可通行"的建筑并摧毁它们(通过测试建筑周围的免费区域来完成)
- 重复此步骤,直到您拥有所需数量的建筑
之所以会出现无休止的循环,是因为Destroy
实际上并没有破坏任何东西——它只是在帧的末尾标记要破坏的对象。问题是整个循环都是在一帧中运行的,所以实际的破坏永远不会发生。通过这种方式,"不可用"的数量只是随着每次迭代而不断增长。
有许多快速方法可以解决此问题,还有一种好方法 快速方式有: 使用 将循环转换为跨多个帧运行的协同程序,这样 好的方法是考虑算法的替代实现。与其先放置建筑,然后摧毁放置不好的建筑,不如试着为建筑找到一个好的位置,然后再放置。最好这样做,因为即使你克服了DestroyImmediate
:http://docs.unity3d.com/ScriptReference/Object.DestroyImmediate.html.只要确保你知道自己在做什么。Destroy
将有时间实际运行,并且您将实时看到场景生成。Destroy
函数的问题,你的算法仍然有一个逻辑问题:如果你根本没有足够的空间容纳所有建筑怎么办?您不知道何时停止当前的实现。你们只会在一个无限循环中不断地生成和摧毁建筑。