x


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?

more ▼

asked Nov 15, 2010 at 04:30 PM

xeophin gravatar image

xeophin
383 26 25 38

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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;
     }
 }

}

more ▼

answered Nov 15, 2010 at 04:42 PM

duck gravatar image

duck ♦♦
47.7k 131 230 471

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

Nov 15, 2010 at 04:58 PM xeophin
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x129
x60

asked: Nov 15, 2010 at 04:30 PM

Seen: 1444 times

Last Updated: Nov 15, 2010 at 04:30 PM