Procedural Mesh problem from Editor Window

Here is the method to generate cube collected over internet:

    static void CreateCube()
    {
        Vector3[] vertices = {
            new Vector3 (0, 0, 0),
            new Vector3 (1, 0, 0),
            new Vector3 (1, 1, 0),
            new Vector3 (0, 1, 0),
            new Vector3 (0, 1, 1),
            new Vector3 (1, 1, 1),
            new Vector3 (1, 0, 1),
            new Vector3 (0, 0, 1),
        };

        int[] triangles = {
            0, 2, 1, //face front
			0, 3, 2,
            2, 3, 4, //face top
			2, 4, 5,
            1, 2, 5, //face right
			1, 5, 6,
            0, 7, 4, //face left
			0, 4, 3,
            5, 4, 7, //face back
			5, 7, 6,
            0, 6, 7, //face bottom
			0, 1, 6
        };

        GameObject tem = new GameObject("MUA-OSM Custom Mesh");
        tem.AddComponent<MeshFilter>();



        Mesh mesh = tem.GetComponent<MeshFilter>().mesh;
        mesh.Clear();
        mesh.vertices = vertices;
        mesh.triangles = triangles;
        mesh.Optimize();
        mesh.RecalculateNormals();
    }

When I call this method, it gives me error :

Instantiating mesh due to calling MeshFilter.mesh during edit mode. This will leak meshes. Please use MeshFilter.sharedMesh instead.
UnityEngine.MeshFilter:get_mesh()

And when finally I change Mesh mesh = tem.GetComponent().mesh; to Mesh mesh = tem.GetComponent().sharedMesh;

It gives me another error, saying :

NullReferenceException: Object reference not set to an instance of an object

I clicked on the Console and it referred me to the same line.

Because you did not create any mesh yet. You should do:

Mesh mesh = new Mesh();
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.Optimize();
mesh.RecalculateNormals();
mesh.RecalculateBounds();

GameObject tem = new GameObject("MUA-OSM Custom Mesh");
MeshFilter mf = tem.AddComponent<MeshFilter>();
mf.sharedMesh = mesh;

You forget the important RecalculateBounds as well. Though you should realise that the mesh you’re going to create here is not a cube mesh. A single vertex can only have one vertex normal. So your “cube” will look more like a sphere when it comes to shading the faces. In order to have a cube mesh to actually look like a cube you need 24 vertices (4 vertices per face, so 6*4 == 24). This is exactly what the default Unity cube mesh looks like. Apart from the vertex normals if you want to have a texture mapped onto the faces you need to specify UV coordinates as well. Again those have to be specified per vertex. So another reason why a single face need to have it’s own vertices.