Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections.Generic;
- using UnityEngine;
- public class SingleCubeGenerator : MonoBehaviour
- {
- [SerializeField] MeshFilter _meshFilter = null;
- // we use the values 24 and 36 because there are 6 * 4 vertices (24) and 6 * 6 triangle indices (36)
- private Vector3[] _vertices = new Vector3[24];
- private Vector3[] _normals = new Vector3[24];
- private Vector2[] _uvs = new Vector2[24];
- private int[] _triangles = new int[36];
- void Start()
- {
- PopulateBuffers();
- if (_meshFilter.sharedMesh == null)
- _meshFilter.sharedMesh = new Mesh();
- var mesh = _meshFilter.sharedMesh;
- // we clear in case this is an existing mesh.
- mesh.Clear();
- // we use the Set* methods because they are less heavy than the normal properties!
- mesh.SetVertices(_vertices);
- mesh.SetNormals(_normals);
- mesh.SetUVs(0, _uvs);
- mesh.SetTriangles(_triangles, 0);
- }
- void PopulateBuffers()
- {
- // Set some counters to use in the CreateQuad method
- var vertexCount = 0;
- var triangleCount = 0;
- // Top face
- CreateQuad(
- new Vector3(-.5f, .5f, -.5f),
- new Vector3(-.5f, .5f, .5f),
- new Vector3(.5f, .5f, .5f),
- new Vector3(.5f, .5f, -.5f),
- Vector3.up,
- ref vertexCount,
- ref triangleCount);
- // Bottom face
- CreateQuad(
- new Vector3(.5f, -.5f, -.5f),
- new Vector3(.5f, -.5f, .5f),
- new Vector3(-.5f, -.5f, .5f),
- new Vector3(-.5f, -.5f, -.5f),
- Vector3.down,
- ref vertexCount,
- ref triangleCount);
- // Front face
- CreateQuad(
- new Vector3(.5f, -.5f, .5f),
- new Vector3(.5f, .5f, .5f),
- new Vector3(-.5f, .5f, .5f),
- new Vector3(-.5f, -.5f, .5f),
- Vector3.forward,
- ref vertexCount,
- ref triangleCount);
- // todo: implement remaining faces
- }
- void CreateQuad(Vector3 a, Vector3 b, Vector3 c, Vector3 d, Vector3 normal, ref int vertexCount, ref int triangleCount)
- {
- _vertices[vertexCount + 0] = a;
- _vertices[vertexCount + 1] = b;
- _vertices[vertexCount + 2] = c;
- _vertices[vertexCount + 3] = d;
- _normals[vertexCount + 0] = normal;
- _normals[vertexCount + 1] = normal;
- _normals[vertexCount + 2] = normal;
- _normals[vertexCount + 3] = normal;
- _uvs[vertexCount + 0] = new Vector2(0, 0);
- _uvs[vertexCount + 1] = new Vector2(0, 1);
- _uvs[vertexCount + 2] = new Vector2(1, 1);
- _uvs[vertexCount + 3] = new Vector2(1, 0);
- _triangles[triangleCount + 0] = vertexCount + 0;
- _triangles[triangleCount + 1] = vertexCount + 1;
- _triangles[triangleCount + 2] = vertexCount + 2;
- _triangles[triangleCount + 3] = vertexCount + 2;
- _triangles[triangleCount + 4] = vertexCount + 3;
- _triangles[triangleCount + 5] = vertexCount + 0;
- vertexCount += 4;
- triangleCount += 6;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement