Reputation: 107
So I have been trying to make a Minecraft-like infinite and dynamic world generation and have been using Perlin Noise to get a random but smooth terrain. I'm using Unity (version 5.0.2f1, at this time) so excuse any non-pure-JavaScript things.
(Just to be safe, I'll remind the folks who aren't familiar with Unity Game Engine that Start()
is called the first frame and yield;
tells the engine to move on to the next frame without waiting for completion.)
What happens is that both the Start()
function and the constructor actually work but the constructor fails to call GenerateFloor()
.
Any help is appreciated. Thanks from now.
The code (UnityScript):
#pragma strict
/*
This creates only one chunk so it should be called once for each chunk to be generated
*/
var size = 256; //"Blocks" in a chunk, note that a chunk has to be a square prism because the size is square rooted to generate each side.
var x : float;
var y : float;
var z : float;
var currentX : float;//Note : The first block in the
var currentZ : float;//chunk is (0, 0) and not (1, 1).
public var seed : int;
var heightMap : Vector3[];
print(Mathf.PerlinNoise(currentX, currentZ));
function Start(){
TerrainGenerator(new Vector3(10, 20, 30));
print("Start() is working"); //For debug
}
function TerrainGenerator(coords : Vector3){
x = coords.x;
y = coords.y;
z = coords.z;
print("Constructor worked.");//For debug
}
function Generate(){
GenerateFloor();
GenerateCaves();
}
function GenerateFloor(){
print("GenerateFloor() was called");//For debug
if(!(seed > 0)){
Debug.LogError("Seed not valid. Seed: " + seed + " .");
seed = Random.Range(0, 1000000000000000);
Debug.LogError("Generated new seed. Seed: " + seed + ".");
}
for(var i = 0; i < heightMap.length; i++){
if(currentX == Math.Sqrt(size)){
currentX = 0;
currentZ++;
}
else if(currentX > Math.Sqrt(size)) Debug.LogError("How did this happen?! currentX = " + currentX + " size = " + size + " .");
var height = Mathf.PerlinNoise(currentX, currentZ);
heightMap[currentX * currentZ] = new Vector3(currentX, height, currentZ);
print("For loop worked");//For debug
yield;
}
}
function GenerateCaves(){
//Coming soon
}
Upvotes: 0
Views: 1605
Reputation: 627
You are not supposed to use Constructors with Unity as Unity itself will create the instance and then call the Start() function. Use Start() and Awake() to do what you would usually do in a constructor(like calling your terrain generation function). I'd also strongly suggest that you pick up c#.
So my approach here would be, set x,y,z and size in the inspector of the GameObject to which your script is attached to. Then in Start() call the Generate() function.
Upvotes: 1