Error: trying to create a MB using "new" keyword...

I’m trying to generate a minecraft look-alike terrain.

Here’s the supperclass/sprite to create a block:

private GameObject blockObject;
	
	protected string name;
	protected float size;
	protected Color blockColor;
	protected Vector3 position;

	...

	public void Place(Vector3 blockPos)
	{
		position = blockPos;
		
		blockObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
		blockObject.renderer.material.color = blockColor;
		blockObject.transform.localScale = new Vector3(size, size, size);
		blockObject.transform.position = position;
	}

An example of a GrassBlock:

public class GrassBlock : BlockSprite 
{
	public GrassBlock()
	{
		name = "grassBlock";
		size = 1;
		blockColor = Color.green;
	}
}

And now I want to generate a Chunk, when the “A” button is pressed:

private BlockSprite[, ,] blocks;

private GrassBlock grassBlock = new GrassBlock();
private DirtBlock dirtBlock = new DirtBlock();

public int chunkSize = 10;

public int ChunkSize {
	get {
		return this.chunkSize;
	}
	set {
		chunkSize = value;
	}
}
public ChunkGenerator()
{
	blocks = new BlockSprite[10, 10, 10];
	GenerateTopChunk();
}

public void GenerateTopChunk()
{
	for(int y = 0; y < chunkSize; y++)
	{
		for(int z = 0; z < chunkSize; z++)
		{
			for(int x = 0; x < chunkSize; x++)
			{
				if(y < chunkSize - 1)
				{
					blocks[x, y, z] = new DirtBlock();
				}
				else
				{
					blocks[x, y, z] = new GrassBlock();
				}
			}
		}
	}
}
    public void PlaceBlocks(Vector3 position)
{
	for(int y = 0; y < ChunkSize; y++)
	{
		for(int z = 0; z < chunkSize; z++)
		{
			for(int x = 0; x < chunkSize; x++)
			{
				blocks[x, y, z].Place(new Vector3(x, y, z));
			}
		}
	}
}
void Update()
{
	if(Input.GetKeyDown(KeyCode.A))
	{
		PlaceBlocks(new Vector3(0, 0, 0));
	}
}

But whenever I start the game I get 999+ warnings: You are trying to create a MonoBehaviour using the ‘new’ keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
UnityEngine.MonoBehaviour:.ctor()
BlockSprite:.ctor()
DirtBlock:.ctor()

So… I’m stuck :open_mouth:

This won’t work if GrassBlock inherits from MonoBehaviour

private GrassBlock grassBlock = new GrassBlock();

You’ll want to declare it like this:

private GrassBlock grassBlock = null;

And then in your Start() function do this:

grassBlock = gameObject.AddComponent<GrassBlock>();

NOTE: If you are implementing minecraft-like terrain you won’t be able to have a gameObject for every cube of the terrain. Be warned.

public ChunkGenerator()
{
blocks = new BlockSprite[10, 10, 10];
GenerateTopChunk();
}

//should probably be

public void ChunkGenerator()
{
    blocks = new BlockSprite[10, 10, 10];
    GenerateTopChunk();
}