Calling class from monobehaviour class

I’ve got a problem when trying to use class not deriving from monobehaviour.

There are 2 classes. The first one, ‘Initialization’, is a Monobehaviour and connected to a GameObject.

public class Initialization : MonoBehaviour {

	// Use this for initialization
	void Start () {
		MineralInitialization.ReadJSON ();
	}

}

The second one, ‘MineralInitialization’, is a class not using Monobehaviour and is not connected to a GameObject.

public static class MineralInitialization {

	private static List<Mineral> minerals;

	public static void ReadJSON() {
		using(StreamReader r = new StreamReader("Assets/Scripts/Config/test.json")) {
			string json = r.ReadToEnd();
			minerals = JsonConvert.DeserializeObject<List<Mineral>> (json);
		}

		foreach (var m in minerals) {
			Debug.Log (m.Name);
		}
	}

}

Every time I run this the functionality is working perfectly fine, but the following warning arises multiple times. :

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

In my eyes I’ve done exactly what Unity asks me to do, but obviously I did something wrong. Hope you guys can help. Thanks.

I’m guessing that Mineral is a MonoBehaviour. You can’t use regular serialization with Monobehaviours, since you have to use Instantiate or AddComponent instead of new.

Your problem is in this line:

minerals = JsonConvert.DeserializeObject<List<Mineral>> (json);

JsonConvert.DeserializeObject internally uses “new” to create instances, giving you the error message. You’ll have to use another way to save your MonoBehaviour objects.

What you need to do is save the object’s properties manually, then instance the objects yourself and then load the saved data.