Created
July 28, 2020 06:21
-
-
Save Ardaurum/299b1b316accfd139346c90d4c375251 to your computer and use it in GitHub Desktop.
Serializing mesh in a component
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; | |
namespace Ard.Procedural | |
{ | |
[ExecuteInEditMode] | |
[RequireComponent(typeof(MeshFilter))] | |
public sealed class RuntimeMesh : MonoBehaviour | |
{ | |
[SerializeField] [HideInInspector] private Vector3[] _vertices; | |
[SerializeField] [HideInInspector] private Vector3[] _normals; | |
[SerializeField] [HideInInspector] private Vector2[] _uv0; | |
[SerializeField] [HideInInspector] private Color[] _colors; | |
[SerializeField] [HideInInspector] private int[] _triangles; | |
public void Awake() | |
{ | |
Rebuild(); | |
} | |
public void Serialize(Mesh mesh) | |
{ | |
_vertices = mesh.vertices; | |
_normals = mesh.normals; | |
_uv0 = mesh.uv; | |
_colors = mesh.colors; | |
_triangles = mesh.triangles; | |
Assign(mesh); | |
} | |
private void Rebuild() | |
{ | |
Assign(new Mesh | |
{ | |
vertices = _vertices, | |
normals = _normals, | |
uv = _uv0, | |
colors = _colors, | |
triangles = _triangles | |
}); | |
} | |
private void Assign(Mesh mesh) | |
{ | |
mesh.RecalculateBounds(); | |
GetComponent<MeshFilter>().sharedMesh = mesh; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment