2
\$\begingroup\$

Unity's AddComponent() method has an optional parameter of a string. This string is the className. What is the class name? What is it used for? I could not find any documentation on this.

\$\endgroup\$
5
\$\begingroup\$

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: AddComponent("GoToPosition");

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:

  1. It's strongly typed, so I know if I spelled the component name correctly.
  2. 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 AddComponent<GoToPosition>().

\$\endgroup\$
2
4
\$\begingroup\$

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 GetComponent).

The string versions of these functions exist, presumably, for untyped languages that could not use Type (inferred from a generic parameter) like C# can.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.