Documentation

Unity Engine


User Manual

Script Reference

Unity Engine


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

gameObject

The GameObject to add the new component to.

Returns

Type

Description

TThe 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.
public static Component AddComponent(GameObject gameObject, Type type)

Parameters

gameObject

The GameObject to add the new component to.

type

The type of component to create. It must derive from Component.

Returns

Type

Description

ComponentThe 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.

Examples

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