Funny results with Random

Hey Guys,

Im working on a random Room generating script. but when I try to place the exit tile along the X axis of the room I occasionally get some funny results.

public class Room_Generation : MonoBehaviour {

	public GameObject Floor;

	// Use this for initialization
	void Start () {
		CreateRoom();
	}

	void CreateRoom(){
		int iRoomWidth = Random.Range(1,10);
		int iRoomLength = Random.Range(1,10);
		for(int iZ = 0; iZ <= iRoomLength; iZ++){
			for(int iX = 0; iX <= iRoomLength; iX++){
				PlaceTile("Floor ",iX,iZ);
			}
		}
		PlaceExit(iRoomWidth,iRoomLength);
	}
	void PlaceTile (string strName,int iX,int iZ){
		int iTileSpacing = 4;
		GameObject gFloor = Instantiate(Floor) as GameObject;
		gFloor.transform.parent = transform;
		gFloor.transform.localPosition = new Vector3(iX,0,iZ) * iTileSpacing;
		gFloor.name = strName + iX + "," + iZ;	
	}
	void PlaceExit (int iRoomWidth, int iRoomLength){
		int iRandomX = Random.Range(0,iRoomWidth);
		PlaceTile("Door ",iRandomX, -1);
	}
}

When its placing the door tile it makes a random number between 0 and the room width and then just place the tile on that X axis with -1 in the Z axes. But from this attached picture the random X number turned out to be 5 some how even when the room width is only 1.

18678-capture.jpg

Any Idea?

I don't see a smoking gun here, but there are a couple of things for you to look at. The screenshot shows the global position of objects, but your PlaceTile() function is placing the object using the 'localPosition'. Your tile will be relative to the parent rather than a world position. The second thing to look at is the difference beweeen the integer and floating point version of RandomRange(). The integer version is exclusive of the final value. I cannot tell if that is an issue with your code or not.

Keep in mind that when you use localPosition, placement will be both relative to the parent, and in the coordinate system defined by the parent. So if the parent is turned 90 degrees, it won't appear on the axes you expect it to. If the parent's scale is non-zero, then its position will be scaled accordingly.

The Parent is at 0,0 and not rotated so that shouldn't be it. Ill investigate the Ramdom.Range integer and see what I can find.

Another thing to try: either add some Debug statements (to see what values are actually being generated / used) or use MonoDevelop / Visual Studio to debug your code line by line: http://docs.unity3d.com/Documentation/Manual/Debugger.html

1 Answer

1

I believe I found the issue. Both for loops were using iRoomLength, iX should be using iRoomWidth;

for(int iZ = 0; iZ <= iRoomLength; iZ++){ 
    for(int iX = 0; iX <= iRoomLength; iX++){

Yay!