Description
The GetOrAddComponent<T>
method is a generic method of the GameObject
class that attempts to retrieve 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
, specifying 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 on myGameObject
. 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 or add a component of type MyComponentType
MyComponentType component = myGameObject.GetOrAddComponent<MyComponentType>(true);
// The component is now guaranteed to be on the GameObject, and it is enabled if it was newly added.