Hey im trying to get an object which is referenced in another script (dictionary). But when i try to get the object in the start method it seems like the dictionary isnt populated jet. Error: NullReferenceException: Object reference not set to an instance of an object
If I run this line of code in the update method it works completely fine.
Is there an easy way to let this line run after the dictionary is populated?
Grid Manager Script
Camera Movement Script
CodePudding user response:
Both your code snippets run in Start
.
There is no way to predict in which order these two Start
messages will be invoked (at least not from the user perspective).
To solve this kind of race conditions (see Order of execution for event functions).
The Awake function is called on all objects in the Scene before any object's Start function is called.
my general thumb-rule is:
Use
Awake
to initialize the component itself where it doesn't depend on values from other components.
E.g. initializing your fields, filling your collections, using
GetComponent
etc to initialize references (but stop there)Use
Start
to then initialize things where you do depend on other components being already initialized.Like in your case access the collections of the other component
This usually covers most of the cases.
In your case simply converting GridManager.Start
to GridManager.Awake
should already solve the issue.
Where this is not enough you either can start and tweak the Script Execution Order and basically enforce a certain order in which the event methods get invoked or implement a more complex event based initialization system
CodePudding user response:
Populate the dictionary in Awake() method instead of Start(), then it would be ready by the time you need it in Start() of another script.