List of Monobehaviour clasess, Editor

I have 2 scripts. SpawnerM2 and SpawnerM2Editor.

First script contains 2 clases:

[System.Serializable]
public class SpawnerM2Single : MonoBehaviour
{
	// some variables

	void Update () 
	{
		// some code
	}
}
 
[System.Serializable]
public class SpawnerM2 : MonoBehaviour 
{
	public List<SpawnerM2Single> single = new List<SpawnerM2Single>();
}

second script:

[CustomEditor(typeof(SpawnerM2))]
public class SpawnerM2Editor : Editor 
{
	private SerializedObject spawnerM2SO;
	private SpawnerM2 mySpawnerM2;
	
	void OnEnable () 
	{
		spawnerM2SO = new SerializedObject(target);
		mySpawnerM2 = (SpawnerM2)target;
	}
	
	public override void OnInspectorGUI () 
	{
		spawnerM2SO.Update();
		
		EditorGUILayout.BeginVertical();
		
			int i = 0;
			
			foreach(SpawnerM2Single sp in mySpawnerM2.single)
			{
				EditorGUILayout.Foldout(true,"Spawner #" + i);
				{  
					// some code
				}
				i++;

			}
		
		EditorGUILayout.EndVertical();
		
		if (GUILayout.Button("Add spawner")) 
		{
			// ERROR HERE
			mySpawnerM2.single.Add(new SpawnerM2Single());
		}
		
		if (GUILayout.Button("Remove last spawner") && mySpawnerM2.single.Count > 0) 
		{
			mySpawnerM2.single.RemoveAt(mySpawnerM2.single.Count-1); 
		}
		
		if(GUI.changed)
		{
			EditorUtility.SetDirty(target);
			EditorUtility.SetDirty(mySpawnerM2);
		}
		
		spawnerM2SO.ApplyModifiedProperties();
	}    
}

I get an error message:

You are trying to create a MonoBehaviour using the ‘new’ keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
UnityEngine.MonoBehaviour:.ctor()
SpawnerM2Single:.ctor()
SpawnerM2Editor:OnInspectorGUI() (at Assets/Editor/SpawnerM2Editor.cs:57)
UnityEditor.DockArea:OnGUI()

How Can I change the code to make it works

Hi, to create a MonoBehavior based class you should not use “new SpawnerM2Single()”, Unity needs to create the object itself.

You can create a new gameObject and then add Components to it like described here: Unity - Scripting API: GameObject.GameObject. You can also Instantiate an existing prefab, in the Editor using: Unity - Scripting API: PrefabUtility.InstantiatePrefab

Also, btw, you don’t need to add [System.Serializable] to a Monobehavior-based class.