Documentation

Unity Engine


User Manual

Script Reference

Unity Engine


AddComponent

Creates a new component and adds it to the specified GameObject.
Read time 1 minuteLast updated 4 days ago

Definition

  • Type: Method
  • Namespace: UnityEditor
  • Assembly: UnityEditor.CoreModule

AddComponent<T>(GameObject)

Creates a new component and adds it to the specified GameObject.
public static T AddComponent<T>(GameObject gameObject) where T : Component

Parameters

gameObject

The GameObject to add the new component to.

Returns

Type

Description

TReturns the component that was created and added to the GameObject.

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

AddComponent(GameObject, Type)

Creates a new component and adds it to the specified 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 and add to the GameObject.

Returns

Type

Description

ComponentReturns the component that was created and added to the GameObject.

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