Unity's AddComponent() method has an optional parameter of a
string is the
className. What is the class name? What is it used for? I could not find any documentation on this.
It's the class name of the component you want to add. For example, if you created a MonoBehaviour script named
GoToPosition and wanted to add it to a game object via script you would call:
That being said, this isn't typically a method I use. I'd rather be explicit about it and use the alternate method of adding components:
AddComponent<GoToPosition>(). This ensures a few things:
- It's strongly typed, so I know if I spelled the component name correctly.
- If I change the name of the component, I can confirm the name changes everywhere (doesn't work as well when the name is a string)
Now, that being said. The text version does have advantages. I've used it when creating a system for externally scripting entities. In that case, I can just add the names of the components I want to add to an entity in an external text file. Then I can use the text version of
AddComponent to easily add the components to entities when parsing the external text file. It's kind of a shortcut for using reflection to find the component class myself.
Both have their uses, but in most cases, you should use the generic type method
It appears to just be the name of the type of component, used to look up which actual object to create or which component to get (later, when you called
The string versions of these functions exist, presumably, for untyped languages that could not use
Type (inferred from a generic parameter) like C# can.