Unity3d c#: instantiate a class that derives from MonoBehaviour

The example bellow works but it gives me the following message on the console:

“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”

Is the warning a serious problem or is there a better way to code this?

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour
{
  Move move = new Move();

  void Update()
  {
    move.Printing();}
  }

public class Move: MonoBehaviour
{
  public int number = 5;

  public void Printing()
  {
    print(number);
  }
}

thank you.

As the message says, you cannot instantiate a MonoBehaviour using the new keyword. MonoBehaviours get instantiated automatically if they are attached to a GameObject that is already in the scene i.e. it’s already inside the hierarchy.

So, typically, you’d have to get a reference to the Move script instance with either of the following ways:

  1. Create a public variable: public Move move; and drag and drop the GameObject, which has the Move script attached, on the Inspector field.
  2. Use GetComponent() to dynamically get a reference to the script, after probably searching for a particular GameObject in the scene e.g. by Using FindGameObjectWithTag()

Use:

 AddComponent<Type>();

if you need to recreate the constructor with parameter use a Init method:

MyType myInstance = gameObject.AddComponent<MyType>();
myInstance.Init(param1, param2);