Performance of Properties vs Setting Fields in Start()

Usually, I would access other `GameObjects` and their components using a construction like this:

public class SomeClass : MonoBehaviour {

    public SomeOtherClass soc;

    void Start() {
        soc = GameObject.FindObjectWithTag("foo").GetComponent<SomeOtherClass>();
    }
}

Now I've run into the situation that some game objects are not yet in then scene at the moment that `Start()` runs.

So I wondered whether I could rewrite the whole thing as such:

public class SomeClass : MonoBehaviour {

    public SomeOtherClass soc {
        get { 
           return GameObject.FindObjectWithTag("foo").GetComponent<SomeOtherClass>();
        }
    }
}

The question of course is whether this will affect performance; even more so when several of those properties are chained and are called from within an `OnGUI()` method. What would you suggest?

1 Answer

1

It would affect performance, proportional to how many times that function is being called. However, there's a happy middle ground which might fit your situation, which is to use a private variable to store the result, and only do the "Find" if the private variable hasn't yet been populated.

You could also use this opportunity to check whether the "foo" gameobject exists yet, and therefore avoid throwing a null reference error.

For example:

public class SomeClass : MonoBehaviour {

    private SomeOtherClass _soc;

    public SomeOtherClass soc {
        get {
            if (_soc == null) {
                GameObject foo = GameObject.FindObjectWithTag("foo");
                if (foo != null) {
                    _soc = foo.GetComponent<SomeOtherClass>();
                }
            }
            return _soc;
        }
    }
}

Thanks looks like an elegant solution (and basically, I should have been able to fid that out myself oh well). goes back to coding