I have a class where I am instantiating another class like so:
public class MyClass : MonoBehaviour{
MyOtherClass obj_otherClass = new MyOtherClass();
}
But for some reason it spits out a warning that reads:
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()
BackgroundSurvey:.ctor()
MyOtherClass:.ctor()
What do I need to do in order to fix this issue? Thank you in advance!
I figured it out, at least for my issues:
Step 1: Declare your foreign class as you would normally:
MyOtherClass obj_otherClas;
Step 2:
Initialize it in either Awake() or Start()
void Awake()
{
obj_otherClas = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<MyOtherClass>();
}
Step 3:
you are now free to use the instance and call its methods where you can.
obj_otherClass.myMethod();
You either add MonoBehaviours to a script via the inspector in the Unity editor, or use AddComponent() (obj_otherclass = gameObject.AddComponent() ). Then you put initialization code in either Awake() or Start() - depending on its dependencies.
You’re not allowed to use constructors for MonoBehaviour derived classes because Unity creates and destroys these classes for its own reasons/purposes in the background. It also can’t be created via constructor (especially a default one) because there’s a restriction that every behavior has to be owned by a specified GameObject.
If your class is derived from MonoBehaviour, then you need to create it by adding it to a GameObject. To add it to the current object do this:
MyOtherClass obj_otherClass = (MyOtherClass)gameObject.AddComponent("MyOtherClass");
If you don’t want your class to be a Component, you can derive it from ScriptableObject and instantiate it like this:
MyOtherClass obj_otherClass = (MyOtherClass)ScriptableObject.CreateInstance("MyOtherClass");
If you to instantiate it as you are, you can’t derive it from GameObject or ScriptableObject.