Flat color each triangle in a mesh

Viewed 27

Im trying to make a 'n' sided mesh with a custom color for each triangle, I can select how many sides it has, the radius, and i'm struggling with the color. I want to put a random color on each drawn triangle, now that works, but I don't want it to blend with the other colors, I want it to be a flat color.

Shoud I make a material for each triangle via code and assign it to a triangle?, maybe a shader?. I dont know too much about materials or shaders, but willing to learn, just need to know what would be the best solution and maybe how to apply it.this is an Example of what i want

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

[RequireComponent(typeof(MeshFilter))]
public class CreateSectionMesh : MonoBehaviour {
    //Sides of the Plane
    [Range(3, 100, order = 1)]
    [SerializeField]
    int NumberOfSides = 3;
    //Radius of the plane
    [Range(10, 100, order = 1)]
    [SerializeField]
    int ShapeRadius = 10;

    // Just setup everything from the start to test...
    void Start() {

        Mesh mesh = GetComponent<MeshFilter>().mesh;

        Vector3[] vertices = new Vector3[NumberOfSides + 1];
        //With this I can know the angle for each triangle
        float angle = 2 * Mathf.PI / NumberOfSides;
        vertices[0] = new Vector3(0, 0);
        Color[] colors = new Color[vertices.Length];

        //Set the vertices
        for (int i = 1; i <= NumberOfSides; i++) {
            vertices[i] = new Vector3(Mathf.Sin(i * angle), Mathf.Cos(i * angle)) * ShapeRadius;
        }

        for (int i = 0; i <= NumberOfSides; i++) {
            Debug.LogFormat("Vertices: {0}", vertices[i]);
        }
        
        //Setup the triangles to draw them properly
        int[] triangles = new int[3 * NumberOfSides];
        for (int i = 0; i < NumberOfSides; i++) {
            triangles[3 * i] = 0;
            triangles[3 * i + 1] = i + 1;
            triangles[3 * i + 2] = i + 2 > NumberOfSides ? i + 2 - NumberOfSides : i + 2;
        }

        for (int i = 0; i < triangles.Length; i++) {
            Debug.Log(triangles[i]);
        }

        //Finally the color for each triangle, but is blending with each near driangle color...
        for (int i = 0; i < vertices.Length; i++) {
            colors[i] = new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f));
        }

        mesh.vertices = vertices;
        mesh.triangles = triangles;
        mesh.colors = colors;

        mesh.RecalculateNormals();
        mesh.RecalculateBounds();
        mesh.Optimize();
    }
}

Thanks for the help

0 Answers
Related