Description
The GetOrAddComponent<T>
method is a generic method of the GameObject
class that retrieves a component of type T
from the GameObject
. If the component does not exist, it adds a new component of type T
to the GameObject
. The method also allows you to specify whether the component should be enabled upon creation.
Usage
To use the GetOrAddComponent<T>
method, call it on an instance of GameObject
and specify the type of component you want to retrieve or add. You must also provide a boolean parameter startEnabled
to indicate whether the component should be enabled if it is newly added.
Example usage:
var myComponent = myGameObject.GetOrAddComponent<MyComponentType>(true);
In this example, myComponent
will be assigned the existing component of type MyComponentType
if it exists. If it does not exist, a new component of type MyComponentType
will be added to myGameObject
and enabled.
Example
// Example of using GetOrAddComponent
GameObject myGameObject = new GameObject();
// Attempt to get a component of type MyComponentType
// If it doesn't exist, add it and enable it
MyComponentType component = myGameObject.GetOrAddComponent<MyComponentType>(true);
// Use the component
component.DoSomething();