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
. This method is useful for ensuring that a GameObject
has a specific component, without needing to check for its existence beforehand.
Usage
To use the GetOrAddComponent<T>
method, specify the type of component you want to retrieve or add as the generic type parameter T
. The method also takes a boolean parameter startEnabled
which determines whether the component should be enabled upon creation if it does not already exist.
Example
// Example usage of GetOrAddComponent
// Assuming 'gameObject' is an instance of GameObject
var myComponent = gameObject.GetOrAddComponent<MyComponent>(true);
// 'myComponent' will be the existing component if it exists,
// or a new instance of MyComponent if it doesn't.