- Home /
Why GetComponent()?
Can anyone tell me why you must pass references via GetComponent() and not the new keyword when inheriting from MonoBehaviour? Also why can't you use the static keyword? I am studying c# and still having some trouble with some concepts.
Why would you want to pass an object into GetComponent? That would mean every time you want to use GetComponent you need to make a new object.
You can use the static keyword, what are you talking about???
I have a class that raycasts from the camera to get the position in world space that the mouse is over. In order to get the result for my other classes I need to make a reference. When I call
$$anonymous$$ousePosition mousePosition = new $$anonymous$$ousePosition();
I get an error telling me you can't use the new key word with object inherited from $$anonymous$$onoBehaviour. And if I make the $$anonymous$$ousePosition() class static I get a warning saying I shouldn't, and the script fails to work at runtime. The only thing that works is:
$$anonymous$$ousePosition mousePosition = playerCamera.GetComponent<$$anonymous$$ousePosition>();
I guess what I am asking is why I can't use the new keyword and why it makes errors when you use static with monoBehaviour.
Unity use an object/component model. Game object get components. Components are instances of a class attached to game objects. GetComponent() does not create a new component, it get a reference to an existing component. When you drag a script onto an object, or use Add Component button, or when you use the Component menu, you are creating and attaching an instance of a specific class to a game object. If you wanted to dynamically create a component at runtime, you would use GameObject.AddComponent ins$$anonymous$$d of 'new'. But note you would be creating that object as a component of some game object. You also use Awake() or possibly Start() in place of a tradition class constructor in Unity.
Note you are free to use new and constructors for classes you don't derive from $$anonymous$$onobehaviour.
Your answer
Follow this Question
Related Questions
Error trying to createMonoBehaviour using the 'new' keyword in cSharp script 4 Answers
GetComponent of ALL clones? 2 Answers
You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. 2 Answers
MonoBehaviours can only be added using AddComponent(). Alternatively. 1 Answer
Accessing components/variables? 1 Answer