When to initialize?

This is a really nooby question but I just can’t seem to get my head around it for some reason.

If I have 2 scripts, the second one needs the first to be initialized before it can initialize itself… What is the most effective way of doing this? Every one says to use Start() to initialize but if I were to do that then the second script is attempting to initialize before the first resulting in the variable in question becoming 0.

The way I am currently doing it is only to use the Start() method of the first script, initialize and the BroadcastMessage to the other to give it the green light… I don’t think that is the most efficient way of doing this though, please do correct me if i’m wrong.

Remember that you can use both Start() and Awake(). All Awake() calls will happen before any Start() calls.

I find this approach is portable and simple:

  • Use Awake() to initialize each object’s internals
  • Avoid accessing other objects until Start()

Failing that, you could use script execution order to make sure that one script fires before the other.

A more general approach, not specific to Unity, is to use lazy initialization. If your script initializes itself the first time it’s accessed, you sidestep the problem entirely. This does depend on careful implementation of accessor functions, but it’s handy reading if you’re looking to expand your knowledge.