AddComponent
Creates a new component of type T and adds it to a GameObject.
Read time 1 minuteLast updated 3 days ago
Definition
- Type: Method
- Namespace: UnityEditor
- Assembly: UnityEditor.CoreModule
AddComponent<T>(GameObject)
Creates a new component of type T and adds it to a GameObject.
public static T AddComponent<T>(GameObject gameObject) where T : Component
Parameters
The GameObject to add the new component to.
Returns
Type | Description |
|---|---|
| T | The component that the method created and added. |
Remarks
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 , so you don't need to cast it.
TAddComponent(GameObject, Type)
Creates a new component of the specified type and adds it to a GameObject.
public static Component AddComponent(GameObject gameObject, Type type)
Parameters
The GameObject to add the new component to.
Returns
Type | Description |
|---|---|
| Component | The component that the method created and added. |
Remarks
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 doesn't derive from Component.
typeExamples
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); } }}