| Parameter | Description |
|---|---|
| gameObject | The GameObject to add the new component to. |
| type | The type of component to create. It must derive from Component. |
Component The component that the method created and added.
Creates a new component of the specified type and adds it to a GameObject.
Use this method to add a component in the Unity Editor. The method registers the change with Undo and applies the default values of the project to the new component. The method throws an exception if type doesn't derive from Component.
using UnityEngine; using UnityEditor;
public class CreateComponentExample { [MenuItem("ObjectFactoryExample/Add Camera to Selection")] public void AddDefaultComponentEditor() { if (Selection.activeGameObject != null) { Camera camera = ObjectFactory.AddComponent<Camera>(Selection.activeGameObject); } } }
| Parameter | Description |
|---|---|
| gameObject | The GameObject to add the new component to. |
T The component that the method created and added.
Creates a new component of type T and adds it to a GameObject.
Use this method to add a component in the Unity Editor. The method registers the change with Undo and applies the default values of the project to the new component. This generic overload returns the component as type T, so you don't need to cast it.