Skip to content

Instantly share code, notes, and snippets.

@runewake2
Created December 22, 2017 05:08
Show Gist options
  • Select an option

  • Save runewake2/16e58926ad56d376e15fefe3045330e8 to your computer and use it in GitHub Desktop.

Select an option

Save runewake2/16e58926ad56d376e15fefe3045330e8 to your computer and use it in GitHub Desktop.
Unity3D Script to generate a uniform N sided polygon.
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
[RequireComponent(typeof(MeshFilter))]
public class DynamicUniformPoligon : MonoBehaviour
{
private MeshFilter filter;
public int initialSides = 3;
public float radius = 1;
public Gradient steppedColor;
void Start ()
{
filter = GetComponent<MeshFilter>();
}
void Update ()
{
filter.mesh = GenerateMesh(initialSides);
}
Mesh GenerateMesh(int initialSides)
{
Mesh mesh = new Mesh();
var triangles = new List<int>();
var vertices = new List<Vector3>();
var colors = new List<Color>();
vertices.Add(Vector3.zero);
colors.Add(steppedColor.Evaluate(0));
for (int i = 0; i < initialSides; ++i)
{
float rotation = Mathf.PI * 2 * (i / (float) initialSides);
vertices.Add(new Vector3(Mathf.Sin(rotation), 0, Mathf.Cos(rotation)) * radius);
colors.Add(steppedColor.Evaluate(1));
triangles.Add(0);
triangles.Add(1 + i);
triangles.Add(1 + ((i + 1) % initialSides));
}
mesh.vertices = vertices.ToArray();
mesh.triangles = triangles.ToArray();
mesh.colors = colors.ToArray();
return mesh;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment