Created
November 8, 2021 08:01
-
-
Save LuviKunG/8c85c8c755fa932ce59ac6f97fe5fc9e to your computer and use it in GitHub Desktop.
Mesh Generation scripts for Unity Engine.
This file contains hidden or 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 System; | |
using UnityEngine; | |
namespace Game | |
{ | |
[RequireComponent(typeof(MeshFilter))] | |
[RequireComponent(typeof(MeshRenderer))] | |
public class MeshGeneration : MonoBehaviour | |
{ | |
[SerializeField] | |
protected MeshFilter meshFilter; | |
[SerializeField] | |
protected MeshRenderer meshRenderer; | |
// Vertex position relative to mesh filter position. | |
public Vector3[] vertices; | |
// It's array index of vertices, need to be mod by 3. every 3 points should be order by clockwise. | |
public int[] triangles; | |
private Mesh mesh; | |
protected virtual void Awake() | |
{ | |
mesh = new Mesh(); | |
meshFilter.mesh = mesh; | |
} | |
protected virtual void Start() | |
{ | |
GenerateMesh(); | |
} | |
public void GenerateMesh() | |
{ | |
mesh.Clear(); | |
mesh.vertices = vertices; | |
mesh.triangles = triangles; | |
// I Don't know why this isn't working. Unity still calculate in wrong | |
mesh.RecalculateNormals(); | |
} | |
#if UNITY_EDITOR | |
protected virtual void OnDrawGizmosSelected() | |
{ | |
for (int i = 0; i < vertices.Length; ++i) | |
{ | |
Gizmos.DrawWireSphere(transform.TransformPoint(vertices[i]), 0.01f); | |
UnityEditor.Handles.Label(transform.TransformPoint(vertices[i]), $"{i}:{vertices[i]}", UnityEditor.EditorStyles.miniBoldLabel); | |
} | |
if (triangles.Length % 3 == 0) | |
{ | |
for (int i = 0; i < triangles.Length && i % 3 == 0; i = i + 3) | |
{ | |
int i1 = i; | |
int i2 = i + 1; | |
int i3 = i + 2; | |
Gizmos.DrawLine(transform.TransformPoint(vertices[triangles[i1]]), transform.TransformPoint(vertices[triangles[i2]])); | |
Gizmos.DrawLine(transform.TransformPoint(vertices[triangles[i2]]), transform.TransformPoint(vertices[triangles[i3]])); | |
Gizmos.DrawLine(transform.TransformPoint(vertices[triangles[i3]]), transform.TransformPoint(vertices[triangles[i1]])); | |
} | |
} | |
} | |
protected virtual void OnValidate() | |
{ | |
if (UnityEditor.EditorApplication.isPlaying) | |
{ | |
try | |
{ | |
if (mesh != null) | |
GenerateMesh(); | |
} | |
catch (Exception e) | |
{ | |
Debug.LogException(e); | |
} | |
} | |
} | |
protected virtual void Reset() | |
{ | |
meshFilter ??= GetComponent<MeshFilter>(); | |
meshRenderer ??= GetComponent<MeshRenderer>(); | |
} | |
#endif | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment