using System.Collections.Generic;
using UnityEngine;

public class MeshTestWithLists : MonoBehaviour
{

    MeshFilter meshFilter;

    // Vertex and tris buffers
    List<Vector3> vertexBuffer;
    List<int> trisBuffer;

    // Reference to the mesh
    Mesh mesh;

    const int MAX_NUM_QUADS = 10;

    void Start()
    {
        meshFilter = gameObject.AddComponent<MeshFilter>();
        gameObject.AddComponent<MeshRenderer>();

        // Create the mesh once, at start
        mesh = new Mesh();
        meshFilter.mesh = mesh;

        // Since we know how many quads we will use, we can predict the maximum possible count
        // and initialize with that count as capacity
        vertexBuffer = new List<Vector3>(MAX_NUM_QUADS * 4);
        trisBuffer = new List<int>(MAX_NUM_QUADS * 6);
    }

    void Update()
    {
        int numOfQuads = Random.Range(2, MAX_NUM_QUADS);

        vertexBuffer.Clear();
        trisBuffer.Clear();

        for (int i = 0; i < numOfQuads; i++)
        {
            Vector3 quadStartPos = Random.insideUnitSphere * 5;

            // Create vertices of the quad, and add a random position to each vertex
            vertexBuffer.Add(quadStartPos + new Vector3(-1, -1, 0) + Random.insideUnitSphere * 0.1f);
            vertexBuffer.Add(quadStartPos + new Vector3(-1, 1, 0) + Random.insideUnitSphere * 0.1f);
            vertexBuffer.Add(quadStartPos + new Vector3(1, -1, 0) + Random.insideUnitSphere * 0.1f);
            vertexBuffer.Add(quadStartPos + new Vector3(1, 1, 0) + Random.insideUnitSphere * 0.1f);

            // Triangles, offset by i * number of vertices for every quad
            trisBuffer.Add(i * 4 + 0);
            trisBuffer.Add(i * 4 + 1);
            trisBuffer.Add(i * 4 + 2);
            trisBuffer.Add(i * 4 + 1);
            trisBuffer.Add(i * 4 + 3);
            trisBuffer.Add(i * 4 + 2);
        }

        // Because number of vertices changes before triangles, this will cause an error,
        // therefore we want to clear the mesh before assigning data
        mesh.Clear();

        mesh.SetVertices(vertexBuffer);
        mesh.SetTriangles(trisBuffer, 0);
    }
}