I am calling on the variables in a game master object a lot and have lots of code like this:
gMaster.GetComponent("gameMaster").var1 = 0;
gMaster.GetComponent("gameMaster").var2= 0;
gMaster.GetComponent("gameMaster").var3 = 0;
Is there a way to do it without using the “gMaster.GetComponent(“gameMaster”)” so many times? Is it wasteful to be doing it like this or does it not really matter?
You can cache the GetComponent call so you only run it once
var cachedGMaster = gMaster.GetComponent("gameMaster");
cachedGMaster.var1 = 0;
cachedGMaster.var2= 0;
cachedGMaster.var3 = 0;
Also, using the class name without quote is faster than sending a string along. You should only use the string version of GetComponent if you can’t use the class version for some reason (i.e. if you’re attempting to call a C# function from JS, or something like that)
You might consider making GameMaster a public variable and set it in the Unity properties window. That would keep you from having to use GetComponent at all.
Thanks guys for your response. Good tips to help me work more neatly!
Do we know enough about the compiler though to say that it isn’t doing this automatically? It might be, depending on how well it optimizes.
GetComponent is almost certainly using runtime data that the compiler couldn’t know about at compile time (ie, the compiler wouldn’t be able to predict that GetComponent wasn’t returning different values from each call).
And unless I’m mistaken, yours was the 50,000th post on this forum. Maybe you’ll get a prize or something 
It doesn’t do this automatically. If you put together a demo project with GetComponent in a loop that runs many times per frame. Then use the above solution. You will see a frame rate increase. GetComponent is dog slow.
This advice has come straight from Joachim (I think) at some point or another. So… yes. 
The idea of “caching” the call is to declare the component you want to use as a global variable in the script, do the GetComponent call ONCE in the Start or Awake function, and then use the variable in Update, etc.