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. Pass a boolean value to the startEnabled
parameter to determine if the component should be enabled when added.
Type Parameters:
T
: The type of component to retrieve or add. This must be a type that inherits from Component
.
Parameters:
startEnabled
(Boolean): If true
, the component will be enabled when added. If false
, it will be added in a disabled state.
Returns:
T
: The component of type T
that was retrieved or added.
Example
// Example of using GetOrAddComponent
GameObject myGameObject = new GameObject();
// Attempt to get a Rigidbody component, or add one if it doesn't exist
Rigidbody rb = myGameObject.GetOrAddComponent<Rigidbody>(true);
// The Rigidbody component is now guaranteed to be part of myGameObject
// and is enabled if it was newly added.