using UnityEngine; public class MeshGenerator : MonoBehaviour { void Start() { Mesh mesh = new Mesh(); Vector3[] vertices = new Vector3[4]; vertices[0] = new Vector3(0, 0, 0); vertices[1] = new Vector3(1, 0, 0); vertices[2] = new Vector3(0, 1, 0); vertices[3] = new Vector3(1, 1, 0); int[] triangles = new int[6]; triangles[0] = 0; triangles[1] = 2; triangles[2] = 1; triangles[3] = 2; triangles[4] = 3; triangles[5] = 1; mesh.vertices = vertices; mesh.triangles = triangles; GetComponent().mesh = mesh; GetComponent ().sharedMesh = mesh; } }
using UnityEngine; using System.Collections.Generic; public class TerrainGenerator : MonoBehaviour { public float scale = 1f; public int resolution = 100; private Mesh terrainMesh; void Start() { GenerateTerrain(); } void GenerateTerrain() { MeshFilter filter = GetComponentThis example generates a randomly generated terrain mesh using Perlin noise. It creates a mesh with resolution^2 vertices and resolution^2-2 triangles. It then assigns the mesh to a MeshFilter component on the current game object. The package library used in this example is Unity's core engine.(); terrainMesh = filter.mesh; terrainMesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32; List vertices = new List (); List triangles = new List (); for (int i = 0; i < resolution; i++) { for (int j = 0; j < resolution; j++) { float x = i * scale; float z = j * scale; float y = Mathf.PerlinNoise(i * 0.1f, j * 0.1f) * scale; vertices.Add(new Vector3(x, y, z)); if (i < resolution - 1 && j < resolution - 1) { int i0 = i * resolution + j; int i1 = i0 + 1; int i2 = (i + 1) * resolution + j; int i3 = i2 + 1; triangles.Add(i0); triangles.Add(i2); triangles.Add(i1); triangles.Add(i1); triangles.Add(i2); triangles.Add(i3); } } } terrainMesh.Clear(); terrainMesh.vertices = vertices.ToArray(); terrainMesh.triangles = triangles.ToArray(); terrainMesh.RecalculateNormals(); terrainMesh.RecalculateBounds(); filter.mesh = terrainMesh; } }