Is there any shorthand for obj.GetComponent(MyComponent)
?
It seems obj.transform
and obj.GetComponent(Transform)
are equivalent so why doesn’t obj.myComponent
work?
Is there any shorthand for obj.GetComponent(MyComponent)
?
It seems obj.transform
and obj.GetComponent(Transform)
are equivalent so why doesn’t obj.myComponent
work?
There are shorthands for all the inbuilt components- these exist to make life easier for you. If you really wanted to, in C# you could add extra ones for custom components using extension methods, but that’s really not necessary.
Basically, obj.myComponent
doesn’t work for the simplest of reasons- it just doesn’t exist, because it’s never been defined. Why do you think you don’t see it in the script reference? obj.transform
works because it’s been written already- you could write extra ones yourself but it’d really make things confusing.
Oh, there’s this:
private MyComponent _myComponent;
public MyComponent myComponent
{
get {
if(_myComponent == null)
{
_myComponent = GetComponent<MyComponent>();
}
return _myComponent;
}
}
Then, you can use the shortcut:
myScript.myComponent
inside the script where you have this defined.
Or, there’s this:
public static MyComponent myComponent(this MonoBehaviour script)
{
return script.GetComponent<MyComponent>();
}
(used like this)
anyMonoBehaviourScript.myComponent();
but that’s just stupid.