Where should you initialize a script reference?

I was reading this thread about setting a script reference in the inspector versus using GetComponent for the Unit script. If you do use GetComponent for Unit specifically (which derives from NetworkBehaviour), which type of Start/Awake method should you put it in (should it be initialized on server and/or client and which methods achieve those)?

It seems to work in Awake for me:

void Awake()
    unitMovement = GetComponent<UnitMovement>();
1 Like

It’s one of those, it depends kind of answers.

It depends on the circumstances.

OnEnable() / OnDisable()

Then there’s on demand.

It depends.

1 Like

What about OnStartServer, OnStartClient, or OnStartAuthority? When should they be used and how do those differ from Start or Awake?

Yeah, even those networked starts.

When it’s appropriate based on the needs of your project.

They trigger based on what the networking code has them do. You should read the appropriate docs. Mirror right?

I saw the network callbacks in the Mirror docs. What is the difference in initializing the script reference in any of these methods and what potential issues could you run into?

You’ll have to read the docs and figure that out.

When you are accessing something from the same gameObject, it is okay to do this in Awake since you know that the attached component is there already on the gameObject.

So if you are trying to get hold of a Unit component on the same gameObject, you can (and maybe should) do this during awake. There is not need to wait for the server or client to be completely initialized.

However, if you want to do something with the Unit, like access it’s network information, that should wait until a later callback like OnServerStart or OnClientStart.

NetworkingBehaviour is an inherited class that inherits from MonoBehaviour, so in this case it has similar rules for when it is setup and when you can access it for non networked behaviour.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms