The sorts of situations people are referring to it being a problem is like say this:
void Update()
{
if(this.GetComponent<MyScript>() != null && this.GetComponent<SomeOtherScript>() != null && this.GetComponent<MyScript>().SomeBoolValue)
{
this.GetComponent<MyScript>().DoSomething(this.GetComponent<SomeOtherScript>().DoSomethingParameter);
}
}
(yes, there are people out there that do basically this)
For starters this logic could be boiled own to:
void Update()
{
var mysc = this.GetComponent<MyScript>();
var myothersc = this.GetComponent<SomeOtherScript>();
if (mysc != null && myothersc && mysc.SomeBoolValue)
{
mysc.DoSomething(myothersc.DoSomethingParameter);
}
}
Reducing the 5 calls down to 2. Why unnecessarily do work that you don’t have to keep doing?
And then there’s the other optimization that people suggest. Since the component is attached to this gameobject, it’s not going anywhere. So you could just cache those in start:
private MyScript mysc;
private SomeOtherScript myothersc;
void Start()
{
mysc = this.GetComponent<MyScript>();
myothersc = this.GetComponent<SomeOtherScript>();
}
void Update()
{
if (mysc != null && myothersc && mysc.SomeBoolValue)
{
mysc.DoSomething(myothersc.DoSomethingParameter);
}
}
But these optimizations aren’t necessarily because “GetComponent is terribly slow”. It’s that ALL work costs time, so why repeat yourself?
Also, it makes it easier to read!
This goes for any operation regardless of GetComponent. May it be sqrt, List.Contains, or whatever.
At the end of the day don’t be avoiding a method because of some boogie man logic of it being slow. If the method does what you need it to do… then it does what you need it to do!
How else are you supposed to get the damage info of the collider you struck? You could have struck 1 of any number of colliders! It’s not like you could cache that somewhere.