- Home /
Instantiate cube in subclass
Hey guys,
I am a beginner in Unity and currently trying to make a simple Minecraft clone. I have three classes. A terrain generation script, a chunk class and a voxel class. I want to instantiate a cube in the voxel class and use it to generate chunks in the terrain generation script. However when I run the code below, the cube is not created. Does anyone know what I am doing wrong?
Here is my terrain generation script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TerrainGeneration : MonoBehaviour {
private Chunk chunk;
// Start is called before the first frame update
void Start() {
chunk = new Chunk();
}
}
here my chunk class:
public class Chunk {
// the three dimensional array for the voxels in the chunk
Voxel[,,] voxels = new Voxel[16, 16, 16];
// Start is called before the first frame update
void Start() {
voxels[0, 0, 0] = new Voxel(0, 0, 0);
}
}
and here my voxel class:
using UnityEngine;
public class Voxel {
private GameObject mesh;
public Voxel(int xPos, int yPos, int zPos) {
mesh = GameObject.CreatePrimitive(PrimitiveType.Cube);
mesh.transform.position = new Vector3(xPos, yPos, zPos);
}
}
Thanks in advance,
Psycho
Answer by toddisarockstar · Dec 28, 2018 at 10:05 AM
there is a problem with your chunk class the start function should only be used in a class derived from monodevelop. you should be using this to initiate the class :
public class Chunk {
// the three dimensional array for the voxels in the chunk
Voxel[,,] voxels = new Voxel[16, 16, 16];
public Chunk() {
voxels[0, 0, 0] = new Voxel(0, 0, 0);
}
}
Answer by ignacevau · Dec 28, 2018 at 10:16 AM
Supposing that these 3 classes are all in separate scripts, then your Voxel
and Chunk
classes need to derive from the MonoBehaviour
class and you need to add using UnityEngine to your Chunk script.
Also, notice that your terrain will be generated, even without the TerrainGeneration script, because of the Start
method in the Chunk
class, you might want to change that to a constructor
public Chunk() {
voxels[0, 0, 0] = new Voxel(0, 0, 0);
}
Your answer
Follow this Question
Related Questions
How to CreatePrimitve Empty 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Initialising List array for use in a custom Editor 1 Answer
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer