Hello, i am trying to create my own terrain, i am trying to achieve this by doing a vector3 array for all the coordinate points of the terrain and then building a mesh from that array. i use 1 script and a custom class with 3 scripts. The problem is that the mesh currently doesn’t want to display on the object using this script
using UnityEngine;
using System.Collections;
public class CreateTerrain : MonoBehaviour {
public Vector3[] TerrainArray;
public Vector2[] TerrainUVs;
// Use this for initialization
void Start ()
{
Mesh mesh = gameObject.AddComponent<MeshFilter>().mesh;
gameObject.AddComponent<MeshRenderer>();
TerrainArray = STerrain.CreateField(20,20);
TerrainUVs = STerrain.CreateUVs(TerrainArray,20,20);
mesh = STerrain.CreateMesh(TerrainArray,TerrainUVs,20,20);
mesh.RecalculateBounds();
mesh.RecalculateNormals();
}
}
This is the custom class required for the script to function
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class STerrain : MonoBehaviour
{
public static Vector3[] CreateField(int width,int length)
{
List<Vector3> List3D = new List<Vector3>();
for( int x = 0 ; x < width ; x++ )
{
for( int z = 0 ; z < length ; z++ )
{
List3D.Add ( new Vector3( x, 0, z ) );
}
}
return List3D.ToArray();
}
public static Vector2[] CreateUVs( Vector3[] field, int width, int length)
{
Vector2[] uvs = new Vector2[width * length];
for( int x = 0 ; x < width ; x++ )
{
for( int z = 0 ; z < length ; z++ )
{
uvs[( x * width ) + z].x = field[( x * width ) + z ].x / width;
uvs[( x * width ) + z].y = field[( x * width ) + z ].z / length;
}
}
return uvs;
}
public static Mesh CreateMesh( Vector3[] field, Vector2[] uvs, int width, int length)
{
Mesh mesh = new Mesh();
int index;
Vector3 point1;
Vector3 point2;
Vector3 point3;
Vector3 point4;
List<int> tris = new List<int>();
for( int x = 0 ; x < width ; x++ )
{
for( int z = 0 ; z < length ; z++ )
{
index = ( x * width ) + z;
while(true)
{
point1 = field[index];
try
{
point2 = field[index + 1];
}
catch(System.IndexOutOfRangeException e)
{
break;
}
try
{
point3 = field[index + width];
}
catch(System.IndexOutOfRangeException e)
{
break;
}
try
{
point4 = field[index + width + 1];
}
catch(System.IndexOutOfRangeException e)
{
break;
}
tris.Add(index);
tris.Add(index + 1);
tris.Add(index + width);
tris.Add(index + width);
tris.Add(index + width + 1);
tris.Add(index);
break;
}
}
}
mesh.vertices = field;
mesh.uv = uvs;
mesh.triangles = tris.ToArray();
mesh.RecalculateBounds();
mesh.RecalculateNormals();
return mesh;
}
}
Honestly i’m really bumed by this because i thought i finally understood how classes in c# worked and now it seems i am on square one again