Last active
June 25, 2022 04:57
-
-
Save Hyperparticle/68586a8834ed6cafd4a1b2ba32ccf6ed to your computer and use it in GitHub Desktop.
Draw a polygon mesh in Unity
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
public class TestPolygon : MonoBehaviour | |
{ | |
private void Start () { | |
// Create Vector2 vertices | |
var vertices2D = new Vector2[] { | |
new Vector2(0,0), | |
new Vector2(0,1), | |
new Vector2(1,1), | |
new Vector2(1,2), | |
new Vector2(0,2), | |
new Vector2(0,3), | |
new Vector2(3,3), | |
new Vector2(3,2), | |
new Vector2(2,2), | |
new Vector2(2,1), | |
new Vector2(3,1), | |
new Vector2(3,0), | |
}; | |
var vertices3D = System.Array.ConvertAll<Vector2, Vector3>(vertices2D, v => v); | |
// Use the triangulator to get indices for creating triangles | |
var triangulator = new Triangulator(vertices2D); | |
var indices = triangulator.Triangulate(); | |
// Generate a color for each vertex | |
var colors = Enumerable.Range(0, vertices3D.Length) | |
.Select(i => Random.ColorHSV()) | |
.ToArray(); | |
// Create the mesh | |
var mesh = new Mesh { | |
vertices = vertices3D, | |
triangles = indices, | |
colors = colors | |
}; | |
mesh.RecalculateNormals(); | |
mesh.RecalculateBounds(); | |
// Set up game object with mesh; | |
var meshRenderer = gameObject.AddComponent<MeshRenderer>(); | |
meshRenderer.material = new Material(Shader.Find("Sprites/Default")); | |
var filter = gameObject.AddComponent<MeshFilter>(); | |
filter.mesh = mesh; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment