Which is faster? Reference through inspector or on Start () ?

Quick question for anyone willing to respond :slight_smile:

When referencing to another script, which method is faster/better?

var myOtherScript : OtherScript; // drag and drop OtherScript in Inspector

or

private var myOtherScript : OtherScript;

function Start () {
    myOtherScript = GetComponent (OtherScript);
}

And what if OtherScript isn’t attached to the same GameObject, using the second method I would have to:

function Start () {
    myOtherScript = GameObject.FindWithTag ("myTag").GetComponent (OtherScript);
}

Wouldn’t that be much slower then just dragging a reference of OtherScript in the Inspector?

Thanks in advance!

Yes they are slower, but it only runs once so it’s unlikely to have a significant effect.

As long as you avoid such calls in Update() (or anything else called repeatedly) you should be fine.

Thanks for the reply! I’m developing for iPhone, so I’ll grab any performance gain as I can :slight_smile:

Drag and drop just leads to unmanageable clutter. Calling GetComponent / Find in-game is slow. Also, there’s no reason to waste battery life. Even if it will only happen once, I don’t like waiting for anything, so I don’t use it except in the Editor. Instead of using Awake/Start(), use Reset()!

Jessy, I agree that Drag and Drop can lead to clutter…I’m not a big fan of it.

I didn’t know I could use Reset() to store instances to other script, I’m gonna give it a try for sure! So if I understand correctly, calling GetComponent/Find in the Reset() function isn’t as slow as calling it in the Start() or Awake() functions?

Thanks for the help!

The Reset function only runs in the editor, so how slow it is or isn’t is irrelevant. But really, unless you have hundreds/thousands of objects, as far as speed goes none of this matters even on a 1st-gen iPhone (which isn’t going to be running hundreds/thousands of objects anyway…).

–Eric

Thanks Eric, that’s what I thought about the speed…I don’t have that many objects at all so it won’t matter in the end.

I’d like to see test results on that. I heard (from one person) that using GetComponent and FindObject at the beginning of their game was delaying the start of the game by a noticeable and undesirable amount. It’s not hard to avoid doing that, so I don’t, and so have no firsthand experience with how bad it is when you don’t serialize everything possible.

These days, I’m only using Awake() for setting up event listeners, and only using Start() for accelerometer calibration and things that need to be randomized.

(I should note that I don’t call Reset() on anything using the drop-down menu, but I still use that function name in case I ever want to. I use a master script that calls Reset() on everything, which is triggered from a menu item.)