Version: Unity 7.0 Alpha (7000.0)
LanguageEnglish
  • C#

ObjectFactory.AddComponent

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

Declaration

public static Component AddComponent(GameObject gameObject, Type type);

Parameters

Parameter Description
gameObject The GameObject to add the new component to.
type The type of component to create. It must derive from Component.

Returns

Component The component that the method created and added.

Description

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

Declaration

public static T AddComponent(GameObject gameObject);

Parameters

Parameter Description
gameObject The GameObject to add the new component to.

Returns

T The component that the method created and added.

Description

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.