# AddComponent

> Creates a new component of type T and adds it to a GameObject.

## Definition

* **Type:** Method
* **Namespace:** [UnityEditor](/engine/7000.0/script-reference/unityeditor.md)
* **Assembly:** UnityEditor.CoreModule

## AddComponent\<T>(GameObject)

Creates a new component of type T and adds it to a GameObject.

```csharp
public static T AddComponent<T>(GameObject gameObject) where T : Component
```

### Parameters

**** (\[GameObject]\(/engine/7000.0/script-reference/unityengine/gameobject)): 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 `T`, so you don't need to cast it.

## AddComponent(GameObject, Type)

Creates a new component of the specified type and adds it to a GameObject.

```csharp
public static Component AddComponent(GameObject gameObject, Type type)
```

### Parameters

**** (\[GameObject]\(/engine/7000.0/script-reference/unityengine/gameobject)): The GameObject to add the new component to.**** (\[Type]\(https\://learn.microsoft.com/dotnet/api/system.type)): The type of component to create. It must derive from [Component](/engine/7000.0/script-reference/unityengine/component.md).

### Returns

| Type                                                                  | Description                                      |
| --------------------------------------------------------------------- | ------------------------------------------------ |
| [Component](/engine/7000.0/script-reference/unityengine/component.md) | 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 `type` doesn't derive from [Component](/engine/7000.0/script-reference/unityengine/component.md).

### Examples

```csharp
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);
        }
    }
}
```
