Instantiating Mesh in edit mode? C#

Good Afternoon, I have been trying to build a mesh in edit mode.

Using MeshFilter.mesh in editor gives error

Instantiating mesh due to calling MeshFilter.mesh during edit mode. This will leak meshes

It recommends using MeshFilter.SharedMesh, I cannot use this as i want each mesh to be a separate object that can be manipulated.

Thanks Again for all your help.

Current Code

using UnityEngine;
using UnityEditor;
using System.Collections;

[ExecuteInEditMode]
[RequireComponent (typeof (MeshFilter))]

public class Generate : MonoBehaviour {

	    private Mesh s;

	    private Vector3[] vertices = {
		new Vector2(0,0),
		new Vector2(0,1),
		new Vector2(1,1),
		new Vector2(1,0)
	    };
	
	    private int[] triangles = {
		0,1,2,
		2,3,0
	    };   
		
		public void Create()
		{
		    MeshFilter meshfilter = gameObject.GetComponent<MeshFilter>();
		   
                    s = meshfilter.mesh; //Error Line//
		    

		    s.name = "S";
		    s.vertices = vertices;
		    s.triangles = triangles;
	    }
}

Assuming your MeshFilter.sharedMesh field doesn’t point to an already valid mesh, just assign s to it instead of the other way around.

GetComponent<MeshFilter>().sharedMesh = s;

Edit - full source:

using UnityEngine;
using UnityEditor;
using System.Collections;

[ExecuteInEditMode]
[RequireComponent (typeof (MeshFilter))]
public class Generate : MonoBehaviour
{

 public Color FillColor;

 private Mesh s;

 private Vector3[] vertices = {
	 new Vector2(0,0),
	 new Vector2(0,1),
	 new Vector2(1,1),
	 new Vector2(1,0)
 };

 private int[] triangles = {
	 0,1,2,
	 2,3,0
 };   

 public void Create()
 {
	 s = new Mesh();
	 GetComponent<MeshFilter>().sharedMesh = s;

	 s.name = "S";
	 s.vertices = vertices;
	 s.triangles = triangles;
 }

 void Start()
 {
	 Create();
 }

 void Update()
 {
	// if Create() hasn't been called yet, the mesh is still null
	if(s == null)
		return;

	 Vector3[] vertice = s.vertices; //Error Line//


	 Color[] colors = new Color[vertice.Length];
	 int i = 0;

	 while (i < vertice.Length)
	 {
		 colors *= FillColor;*
  •   i++;*
    
  • }*

  • s.colors = colors;*
    }
    }