FICHEKK
FICHEKK

Reputation: 829

How to structure terrain generator in unity?

I am learning C# with Unity and I am trying to create terrain generator. I made a class called Terrain which contains an array of class called Chunk. Chunk should be an array of square GameObjects.

The code looks like this:

public class Terrain : MonoBehaviour {

    public Chunk[] terrain;

    // Use this for initialization
    void Start () {
        terrain[0] = new Chunk(0, 0);
    }
}

and class Chunk looks like this:

public class Chunk : MonoBehaviour {

    public int size;
    public GameObject tile;

    private GameObject[] chunk;
    private int xCoord, yCoord;

    public void Create(int chunkX, int chunkY){
        for(int y = 0; y < size; y++) {
            for(int x = 0; x < size; x++) {
                int xCoord = x + chunkX*size;
                int yCoord = y + chunkY*size;

                chunk[x + y*size] = GameObject.Instantiate(tile, new Vector3(xCoord, yCoord), Quaternion.identity);
                x = chunkX;
                y = chunkY;
            }
        }
    }

    //Constructor
    public Chunk(int chunkX, int chunkY) {
        xCoord = chunkX;
        yCoord = chunkY;
    }
}

I get 1 error and 1 warning:

You are trying to create a MonoBehaviour using the 'new' keyword.  This is not allowed.  MonoBehaviours can only be added using AddComponent().


IndexOutOfRangeException: Array index is out of range.

How can I fix this and can you explain in newbie's terms why I can't use new for creating a new chunk. Also, why is array index out of range? Last question, is this structuring any good and how would you improve it or implement it differently?

Upvotes: 0

Views: 465

Answers (1)

Andrius Naruševičius
Andrius Naruševičius

Reputation: 8578

Simply remove : MonoBehaviour from your Chunk class as you do not any behaviour for that. This is just a holder class for your data, and it does not follow (does not need to either) start-update routine that MonoBehaviour extending classes do.

Upvotes: 1

Related Questions