- Home /
Why does this script put Unity into a not responding state?
I can't figure out why this script is constantly crashing Unity and I'm tired of trying to figure it out, I'd like some help.
using UnityEngine; using System.Collections;
public class TerrainGenerator : MonoBehaviour
{
public GameObject voxel;
public float voxelSize;
public float chunkHeight;
public int chunkSize;
float x;
float y;
void Awake ()
{
Mesh mesh = new Mesh ();
Vector3 [] vertices = new Vector3 [4]
{
new Vector3 (0, 0, 0), new Vector3 (voxelSize, 0, 0), new Vector3 (voxelSize, 0, voxelSize), new Vector3 (0, 0, voxelSize)
};
int [] triangles = new int [6]
{
1, 3, 0, 1, 3, 2
};
mesh.vertices = vertices;
mesh.triangles = triangles;
for (float i = 0; i < chunkSize; i += voxelSize)
{
x = 0;
y += 0.1f * voxelSize;
for (float f = 0; f <= chunkSize; f += voxelSize)
{
x += 0.1f * voxelSize;
Vector3 position = new Vector3 (f, Mathf.Round (Mathf.PerlinNoise (x, y) * chunkHeight) * voxelSize, i);
GameObject voxelTransform = (GameObject) Instantiate (voxel, position, Quaternion.identity);
MeshFilter mf = voxelTransform.GetComponent <MeshFilter> ();
mf.mesh = mesh;
}
}
}
}
get rid of the semi-colons after the } on 16 and 20. Are your #s in the Inspector large?
Your chunkSize is probably too high. Remember: your inner for loop is run chunkSize*chunkSize (assu$$anonymous$$g voxelSize is one) times within one frame, and Instantiate isn't the fastest function out there... I don't know how efficient $$anonymous$$athf.PerlinNoise is.
Apparently chunksize was too large, but I think there's something wrong with my code now. When I set chunksize to 1 it for some reason instantiates 6 objects? The problem is that it's generating 6 times as many as it should. and also, my game runs at a very low framerate even with 6 of the GameObjects, why?
Forget what I just said about it spawning 6x as many, I had voxel sets to not 1. But can somebody explain why the game runs so slow with just a few objects? Is it because of how inefficient instantiate is? I am confused. I'm really just messing around and in the end wanted to develop this into just generating one large mesh and store points in a large array.