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.
Example
// Example of using GetOrAddComponent
// Assume 'gameObject' is an instance of GameObject
var myComponent = gameObject.GetOrAddComponent<MyComponent>(true);
// 'myComponent' will be the existing component if it exists,
// or a new component of type MyComponent if it doesn't.