- Home /
Check if cube is in position before placing new cube
Hey I'm trying to build a terrain generator using cubes. I've got a random "hill" segment but when it generates it doubles up some cubes. I attempted to make an if bool type senario to check before placing but it appears to not have worked as well as I hoped.
for(int hillcount =0; hillcount < 15; hillcount++)
{
int randomy = Random.Range(0, maxy);
int randomz = Random.Range(0,maxz);
int maxhilly = randomy + Random.Range (3,10);
int maxhillz = randomz + Random.Range (3,15);
for(int i2y = randomy; i2y < maxhilly; i2y++)
{
for(int i2z = randomz; i2z < maxhillz; i2z++)
{
targetpos = new Vector3(0+i2y,0,0+i2z);
if(checkIfPosEmpty(targetpos))
{
GameObject newcube = (GameObject)Instantiate(cube, new Vector3(0+i2y,1,0+i2z), Quaternion.identity);
newcube.name = "cube y:" + i2y + " z:" + i2z;
//GameObject newcube = (GameObject)Instantiate(cube, new Vector3(0+i2y,1,0+i2z), Quaternion.identity);
//newcube.name = "cube y2:" + i2y + " z2:" + i2z;
}
}
}
}
}
public bool checkIfPosEmpty(Vector3 targetPos)
{
GameObject[] cubes = GameObject.FindGameObjectsWithTag("cube");
foreach(GameObject cube in cubes)
{
if(transform.position == targetPos)
return false;
}
return true;
}
You sure you are tagging them properly?
This is going to be an extremely slow approach btw. I'm not usually one for premature optimization, but this is just painfully slow.
Already been resolved. I honestly am not too concerned with optimization at this point. I'm fairly new and this way is working for me so I'll change it later if I need to.
Your answer
Follow this Question
Related Questions
How To Drag any Cube Using Mouse Click and Moved Only 1 Unit?? 2 Answers
How to check if your cursor is over a cube. 1 Answer
Using Gizmos.DrawWireCube to draw position bounds? 1 Answer
Looping through array to find a specific class? 0 Answers
Programatically check whether a grid is placed inside or outside a closed figure 0 Answers