GetComponent and GameObject.Find in Awake function = huge loss of fps


I have the following script attached to a GuiText to show the remaining ammo of my player:

var gun_script;

function Awake(){

gun_script = GameObject.Find("player").GetComponent(script);

function Update (){

guiText.text = "" + gun_script.ammo_left;

But with this I noticed there's a loss of 300 frames per second, so:

1- What is the fastest way to access variables from another script?

2- Is the GameObject.Find and GetComponent being executed every frame? If so, how could I pre cache the component, for not to have to search it again every frame?

Thanks in advance!

The main problem is this:

var gun_script;

You haven't defined the type, so you're using dynamic typing, which is at least 20X slower than static typing.

Moreover, there's no reason to use Update (which runs every frame) for this. Just make a function that's only called when ammo_left actually changes.

If you care about speed, don't use OnGUI with a GUI.Label; that will just make things slower. OnGUI runs more often than Update, and has to do extra calculations on top of that.

The GetComponent shouldn't be getting called every frame unless you're constantly disabling/re-enabling that particular gameobject every frame. Your FPS loss may be a result of per-frame string manipulation (and maybe guiText does some kind of rasterization of the string every time .text is updated or something). Try updating the guiText.text only when your ammo_left actually changes instead of every frame.

A couple things to try:

  1. Instead of concatenating gun_script.ammo_left to an empty string, use guiText.text = gun_script.ammo_left.ToString(). This will avoid a string manipulation operation.

  2. Instead of using a guiText object in your Update() event, try drawing your text in the OnGUI() event using a call to GUI.Label().