- Home /
AddComponent calls "start" method sometimes?
I'm having a code that looks like this:
void Update() {
if (some_condition) {
some_gameobject.AddComponent("SomeComponent");
some_gameobject.GetComponent("SomeComponent").variable = value;
}
}
And then in SomeComponent I use variable in the start method:
void Start() {
Debug.log(this.variable);
}
The problem I am seeing is that sometimes this.variable has a null value (and it shouldn't be). Is there any chance that the component's start method gets called before the line after addComponent is executed (where variable is initialized)? Please note that this happens pretty rarely (I had to bang my character's head to a wall a lot to reproduce the issue) which make this look like a race issue.
Answer by Owen-Reynolds · Dec 11, 2013 at 08:21 PM
According to the docs and my very limited testing, Start will never give that sort of race condition.
Awake is guaranteed to be called right away (so always after the Add and before the next line.) And Start is guaranteed never to do that -- to only ever run before it's own Update is about to.
I'd guess that sometimes value
really assigned is null.
I added a Debug.log(value) before adding the component and that value isn't null.
Your answer
![](https://koobas.hobune.stream/wayback/20220613123935im_/https://answers.unity.com/themes/thub/images/avi.jpg)