Reference object created in another script.

Hello there,

I’m having a real problem with scripting and I can’t figure out the solution by myself.

I have a script that ‘creates’ the scene, everything is created programmatically, I’ve added that script to the camera, it also creates the object that the camera should follow.

The problem is, I can’t find a way to ‘pass’ that GameObject to another script on the same Camera other than calling GetComponent inside Update() what doesn’t seem very efficient at all. Of course I could check if the var is null inside Update() but that’s bad practice. The proper way imho is to set the variable on Start(). I don’t know if this have something to do with the other script loading first or whatever.

Any ideas?

Thank you in advance.

This is something common I do a lot. I create a C# properly, and if I am accessing it for the first time I will run GetComponent.

/// Access otherScript.
/// This will find otherScript if it hasn't been found yet.
private OtherScript otherScript {
  get {
    if (m_otherScript == null) {
      m_otherScript = GetComponent<OtherScript>() as OtherScript;
    }
    return m_otherScript;
  }
}
private OtherScript m_otherScript;

what i do in such scenarios (generally), is that i use Awake() to pass all the needed gameobjects/information to other scripts…
then i use Start() to start using this newly passed data/info …

Some people say that the lazy initialization method (illustrated by Garth above) is suboptimal because, if a lot of those happen to come up in the middle of gameplay, it could cause a glitch in your framerate. So you sometimes see the recommendation to initialize such stuff in Start instead.

However, in practice, I suspect that it rarely makes any noticeable difference, and there are advantages to lazy initialization. So, I often do it in exactly the same way as Garth.

Wow! Thank you very much guys! :slight_smile:
Yeah, it seems that “lazy initialization” is the way to go, that will surely eat up some extra CPU cycles though, but as JoeStrout said, I think it’s nothing significant.
I think it’s even okay to call GetComponent at every Update() though because it’s in the official examples: http://docs.unity3d.com/Documentation/ScriptReference/GameObject.GetComponent.html but that doesn’t seem very good practice nevetheless.

Yeah, I wouldn’t call GetComponent on every Update() unless it was some weird situation where the components on the object might be changing. Under normal circumstances, it’s easy enough to cache it in a property and reuse it on every frame.