Last active
August 29, 2015 14:01
-
-
Save Munkkeli/699f098bff64569da995 to your computer and use it in GitHub Desktop.
Unity - Simple Mesh Generation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
using System.Collections.Generic; | |
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer), typeof(MeshCollider))] | |
public class MeshGeneration : MonoBehaviour { | |
// Use this for initialization | |
void Awake () { | |
CreateMesh(); | |
} | |
// Create a simple mesh | |
public void CreateMesh() { | |
Mesh mesh = new Mesh(); | |
List<Vector3> verts = new List<Vector3>(); | |
List<int> tris = new List<int>(); | |
List<Vector2> uvs = new List<Vector2>(); | |
for (int x = 0; x < 16; x++) { | |
for (int y = 0; y < 16; y++) { | |
CreateTile(x, y, verts, tris, uvs); | |
} | |
} | |
mesh.vertices = verts.ToArray(); | |
mesh.triangles = tris.ToArray(); | |
mesh.uv = uvs.ToArray(); | |
mesh.RecalculateBounds(); | |
mesh.RecalculateNormals(); | |
gameObject.GetComponent<MeshFilter>().sharedMesh = mesh; | |
gameObject.GetComponent<MeshCollider>().sharedMesh = mesh; | |
} | |
// Create one tile | |
public void CreateTile(int x, int y, List<Vector3> verts, List<int> tris, List<Vector2> uvs) { | |
int i = verts.Count; | |
verts.AddRange(new Vector3[] { | |
new Vector3(x - 0.5f, 0, y - 0.5f), | |
new Vector3(x + 0.5f, 0, y - 0.5f), | |
new Vector3(x + 0.5f, 0, y + 0.5f), | |
new Vector3(x - 0.5f, 0, y + 0.5f), | |
}); | |
tris.AddRange(new int[] { | |
i + 1, i + 0, i + 2, | |
i + 0, i + 3, i + 2, | |
}); | |
uvs.AddRange(new Vector2[] { | |
new Vector2(0, 0), | |
new Vector2(1, 0), | |
new Vector2(1, 1), | |
new Vector2(0, 1), | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment