How do i make sure an Object is initialized before using it ? C#

Hi, I’m writing a network manager which uses a network plugin.

Right after i add the network plugin component script to my object i try to call a method on this component which is not yet initialize.

How do i make sure the object is initialize before using it ?

For example :

NetworkPlugin plugin;
void Start() 
{
   plugin = gameobject.AddComponent<NetworkPlugin>();
   plugin.ConnectToMasterServer();
}

In the plugin there is a an Object that is being initialize in the Start function
But when i call the ConnectToMaster function there is an exception being thrown that the Object is Null

I solved it by using a Coroutine :

NetworkPlugin plugin;
void Start()
{
    plugin = gameobject.AddComponent<NetworkPlugin>();
    
    StartCoroutine("Wait");
}

IEnumerator Wait()
{
    while (plugin.Object == null ) {
		yield return null;		
    }
    plugin.ConnectToMaster();
}

Is there any other way i could do this without the Coroutine ? A callback ?

Maybe try to attach the NetworkPlugin in the Awake() function and use it from Start() ?

Yes, there is another way. First of all you should use “Awake” to initialize a class itself and use “Start” to initialize connections between components.

All Awake methods are called before the first Start is called when you load a scene. Start is actually called right before the first Update. Awake is called at the moment the object is loaded. Awake basically replaces the constructor.

Another way, if for some reason you have to stick to Start, you can change the script execution order. All classes usually belong to the “Default Time”. However there’s it’s not guaranteed in which order Start, Update, … are called. However if you place a specific script above / below the Default Time you can control if it should be initialized first or last.