making a world

Hello everyone,

I wanna make a word in c# but my code doesn’t work properly.

using UnityEngine;
using System.Collections;

public class World : MonoBehaviour
{	
	int xPos = 0;
	int yPos = 0;
	int zPos = 0;

	public int height = 1;
	public int width = 10;
	public int length = 10;
	public GameObject[] blocks;

	void Awake()
	{
		makeWorld();
	}

	void makeWorld()
	{
		for(int w = 0; w < width; w++)
		{
			blocks[w] = GameObject.CreatePrimitive(PrimitiveType.Cube);
			blocks[w].transform.position = new Vector3(xPos,0,0);
			xPos++;
			for(int l = 0; l < length; l++)
			{
				blocks[l] = GameObject.CreatePrimitive(PrimitiveType.Cube);
				blocks[l].transform.position = new Vector3(xPos,0,zPos);
			}
			zPos++;
		}
	}
}

The problem I have is that it doesn’t draw the world correctly.
I am new to c# so if anyone could help me that would be great!
Thanks in advance

In generating a grid of cubes. (and I am not endorsing the way you are doing it, just helping you understand it) You will want to work it out like a grid.

As you progress through each for statement, you are counting from 0 to 9. You have a second variable incrementing as you add each “width”. This of course is correct because you are forcing it that way. In the Length for statement, you create 10 blocks using the X and Z. Z is never incremented during this process. Now, after the length for, you increment z. So your code will produce 1 block in row x at point z and 10 blocks on top of each other at the same coordinates. Now, also, you are creating a block in your width for, which you should not be doing.

Honestly, this is all logic errors. The code creates, but not in the right order.

Below is some code that fixes your problem.

void makeWorld(){
	GameObject[,] blocks = new GameObject[width, length];
	for(int w = 0; w < width; w++){
		for(int l = 0; l < length; l++){
			blocks[w, l] = GameObject.CreatePrimitive(PrimitiveType.Cube);
			blocks[w, l].transform.position = new Vector3(w,0,l);
		}
	}
}

You need to learn more before attempting larger projects. Play a bit. :wink: