-
Notifications
You must be signed in to change notification settings - Fork 34
/
SimpleProceduralCube.cs
81 lines (70 loc) · 1.96 KB
/
SimpleProceduralCube.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/**
* Simple example of creating a procedural 6 sided cube
*/
[RequireComponent (typeof (MeshFilter))]
[RequireComponent (typeof (MeshRenderer))]
public class SimpleProceduralCube : MonoBehaviour {
void Start () {
MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>();
Mesh mesh = new Mesh ();
meshFilter.mesh = mesh;
mesh.vertices = new Vector3[]{
// face 1 (xy plane, z=0)
new Vector3(0,0,0),
new Vector3(1,0,0),
new Vector3(1,1,0),
new Vector3(0,1,0),
// face 2 (zy plane, x=1)
new Vector3(1,0,0),
new Vector3(1,0,1),
new Vector3(1,1,1),
new Vector3(1,1,0),
// face 3 (xy plane, z=1)
new Vector3(1,0,1),
new Vector3(0,0,1),
new Vector3(0,1,1),
new Vector3(1,1,1),
// face 4 (zy plane, x=0)
new Vector3(0,0,1),
new Vector3(0,0,0),
new Vector3(0,1,0),
new Vector3(0,1,1),
// face 5 (zx plane, y=1)
new Vector3(0,1,0),
new Vector3(1,1,0),
new Vector3(1,1,1),
new Vector3(0,1,1),
// face 6 (zx plane, y=0)
new Vector3(0,0,0),
new Vector3(0,0,1),
new Vector3(1,0,1),
new Vector3(1,0,0),
};
int faces = 6; // here a face = 2 triangles
List<int> triangles = new List<int>();
List<Vector2> uvs = new List<Vector2>();
for (int i = 0; i < faces; i++) {
int triangleOffset = i*4;
triangles.Add(0+triangleOffset);
triangles.Add(2+triangleOffset);
triangles.Add(1+triangleOffset);
triangles.Add(0+triangleOffset);
triangles.Add(3+triangleOffset);
triangles.Add(2+triangleOffset);
// same uvs for all faces
uvs.Add(new Vector2(0,0));
uvs.Add(new Vector2(1,0));
uvs.Add(new Vector2(1,1));
uvs.Add(new Vector2(0,1));
}
mesh.triangles = triangles.ToArray();
mesh.uv = uvs.ToArray();
renderer.material = new Material(Shader.Find("Diffuse"));
mesh.RecalculateNormals();
mesh.RecalculateBounds ();
mesh.Optimize();
}
}