- Home /
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 ?
Answer by eitanwass · Oct 02, 2017 at 09:39 AM
Maybe try to attach the NetworkPlugin in the Awake() function and use it from Start() ?
Answer by Bunny83 · Oct 02, 2017 at 09:42 AM
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.
Uhm that's why i said you should use Awake to initialize the class itself and Start to initialize connections between classes. So your plugin should simply be initialized in Awake ins$$anonymous$$d of Start.
Your answer
Follow this Question
Related Questions
Initialising List array for use in a custom Editor 1 Answer
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
An OS design issue: File types associated with their appropriate programs 1 Answer
NullReferenceException: Object reference not set to an instance of an object 3 Answers