Skip to content

Instantly share code, notes, and snippets.

@Ardaurum
Created July 28, 2020 06:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ardaurum/299b1b316accfd139346c90d4c375251 to your computer and use it in GitHub Desktop.
Save Ardaurum/299b1b316accfd139346c90d4c375251 to your computer and use it in GitHub Desktop.
Serializing mesh in a component
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