Alternative to getComponent?

Ive been reading around, and it sounds like getComponent() is fairly slow. In my game (which I would like to port to mobile in the future) I use it fairly often just to check/change a single variable in a script attached to an object. Is there a more efficient way of accomplishing this to increase performance or is this the only option?

Thanks, Any ideas are appreciated.

Lookup “unity getComponent cache.”

Whenever you compute something you’re going to use a few times, you can save it in a variable. Nothing fancy at all. Instead of if(A.magnitude<10 && A.magnitude>3 ... you write float Amag=A.magnitude; if(aMag<10 && Amag>3). If you have to think harder about how and where to save it, the fancy term is “cache-ing” it, like canned goods in a safehouse.

The trick with getCompnenent is, you can declare variables of type Rigidbody, or script names, Renderer… . Then you have a place to save a GetComponent.

But, if you only use it once a every few seconds, maybe not worth the effort and harder to read code.

There’s a few options.

  1. As @hamster said, it’s typically not a terrible thing to do a GetComponent on Start and save it to a variable. Usually performance hits at startup are okay because people expect that games have to load:

     private SomeScript foo;
    
     void Start()
     {
          foo = GetComponent<SomeScript>();
     }
    
  2. If you make a public variable you can drag the gameobject with that component to it in the editor:

     public SomeScript foo;
    
     void Start()
     {
         if(!foo)
             Debug.LogError("No SomeScript component");
     }
    

And then you can drag a gameobject with a SomeScript component on it to the foo slot in the editor

GetComponent is really not particularly slow. You should profile/benchmark first to be sure it’s actually a problem rather than relying on misinformation.