- Home /
GameObject.AddComponent<T> does not really add a Component?
I wanted to attach a data object that was not a Behaviour to act as meta data for the object it was hung on. Reading the documentation, UnityEngine.Component seems like a very good choice for this being that Component's only class level documentation says:
"Base class for everything attached to GameObjects."
So my data class extends Component but I can't add it through script or the inspector to the correct game object I am trying to tag because I get a message (printed as a log message, not an error) saying:
"Can't add script behaviour DataComponent. The script needs to derive from MonoBehaviour!"
I get that my component could be a MonoBehaviour (which works) that just does not do anything but that does not seem right. Also it seems odd that I cannot add a Component to a GameObject with GameObject.AddComponent() when the signature for that is
public T AddComponent<T>() where T: Component
Is this misleading documentation or am I missing something? I thought this worked at one point so did this break in 3.0? I saw a similar post where someone said to use #pragma dowcast but that seems to be a UnityScript thing.
Answer by Mike 3 · Dec 17, 2010 at 04:31 PM
I don't think it's ever worked, MonoBehaviour is the class to use for custom classes, whereas Component is the base class which both MonoBehaviour uses and the built in components (which all have back end support for being added to GameObjects) use.
The reason AddComponent works with components is so that it works with the built in components, it's not suggesting that your own components will work
The Answers link you provided is just a basic Javascript typing problem, in which Mysqlconn is a MonoBehaviour, but because of #pragma strict, can't be automagically cast to the relevant type
Either way - there's no reason to not use a MonoBehaviour for it, they're pretty light objects if you aren't hooking up the event functions (Update etc)
Your answer
Follow this Question
Related Questions
Animation through graphics in FPS controller, weird character controller issue, NEED help! 0 Answers
AI Pathfinding BCE0019: 'GetComponent' is not a member of 'Object'. 1 Answer
GetComponent null reference C# 1 Answer
GetComponent of copies of one gameobject? 0 Answers
How to get script component of an object with out using its name? 2 Answers