Generating Triangle Problem

Hello, i have problem with generating meshes. I wanted to generate triangle but instead i have error.
Well, just look at the code. Im not the expert but at first sight everything looks okay.

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

public class PolygonGenerator : MonoBehaviour {

    public List<Vector3> newVertices = new List<Vector3>();
    public List<int> newTriangles = new List<int>();
    public List<Vector2> newUV = new List<Vector2>();

    private Mesh mesh;

    // Use this for initialization
    void Start () {
        mesh = GetComponent<MeshFilter>().mesh;

        float x = transform.position.x;
        float y = transform.position.y;
        float z = transform.position.z;

        /*
        newVertices.Add(new Vector3(x, y, z));
        newVertices.Add(new Vector3(x+1, y, z));
        newVertices.Add(new Vector3(x+1, y-1, z));
        newVertices.Add(new Vector3(x, y-1, z));

        newTriangles.Add(0);
        newTriangles.Add(1);
        newTriangles.Add(3);
        newTriangles.Add(1);
        newTriangles.Add(2);
        newTriangles.Add(3);
        */

        newVertices.Add(new Vector3(x, y, z)); //0,0
        newVertices.Add(new Vector3(x+1, y, z)); //1,0
        newVertices.Add(new Vector3(x+1, y-1, z)); //1,-1

        newTriangles.Add(1);
        newTriangles.Add(2);
        newTriangles.Add(3);


        mesh.Clear();
        mesh.vertices = newVertices.ToArray();
        mesh.triangles = newTriangles.ToArray();
        mesh.Optimize();
        mesh.RecalculateNormals();
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}

newTriangles.Add(1);
newTriangles.Add(2);
newTriangles.Add(3);
It’ll create triangles that index out of bounds. Try this instead:

newTriangles.Add(0);
newTriangles.Add(1);
newTriangles.Add(2);

I don’t remember if you also need to assign mesh or sharedMesh of the mesh filter for the graphics to update:

 GetComponent<MeshFilter>().mesh = mesh;

But if you have a mesh collider you must update it.

 GetComponent<MeshCollider>().mesh = null; // For the mesh to update we need to clear...
 GetComponent<MeshCollider>().mesh = mesh; // and assign back even if nodifying same mesh

Your code will fail if the MeshFilter have no mesh assigned, worth keeping in mind.