Description
The GetOrAddComponent<T>
method is used to retrieve a component of type T
from the current GameObject
. If the component does not exist, it will be added to the GameObject
. This method is useful for ensuring that a specific component is present on a GameObject
without needing to check for its existence beforehand.
Usage
To use the GetOrAddComponent<T>
method, call it on an instance of a Component
or GameObject
. Specify the type of component you want to retrieve or add as the generic type parameter T
. The startEnabled
parameter determines whether the component should be enabled upon creation if it does not already exist.
Example
// Example of using GetOrAddComponent
public class ExampleComponent : Component
{
public void Initialize()
{
// Ensure that the GameObject has a Rigidbody component
var rigidbody = GetOrAddComponent<Rigidbody>(startEnabled: true);
// Now you can safely use the Rigidbody component
rigidbody.ApplyForce(Vector3.Up * 10);
}
}