- Home /
Issues using the 'new' keyword
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!
Answer by mmangual_83 · Dec 03, 2013 at 07:18 PM
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();
That code doesn't create a new instance, it just locates one that already exists on a gameobject tagged "$$anonymous$$ainCamera". If the instance doesn't already exist, it will just return null.
Answer by WilliamLeu · Dec 03, 2013 at 07:12 PM
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.
Answer by Spinnernicholas · Dec 03, 2013 at 07:25 PM
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.
Your answer
Follow this Question
Related Questions
how to debug in monodevelop 1 Answer
How to draw an arrow from fps contoller 1 Answer
MonoDevelop 4.0.1 won't recognize "UnityEngine" namespace 5 Answers
Mathf.pingpong 4 Answers