- Home /
Problem is not reproducible or outdated
bool field initialization ignored
Hi everyone,
I have two classes that derive from MonoBehaviour, something like this:
public class A : MonoBehaviour {
private B _b;
private void SomeMethod()
{
_b = gameObject.AddComponent<B>();
}
}
public class B : MonoBehaviour {
private bool _foo = true;
private void SomeMethod()
{
Debug.Log(_foo);
}
}
When The debug output in class B tells me that the bool field _foo
is false
, even though I initialized it with true
in the head of the class, which is what I don't get. When I set _foo
to true
in some other method that is called after _b
has been set with the AddComponent
method, everything works as I expect.
Does this have something to do with the fact that _b
is initialized with null
? Does this result in all the field initializations in class B
being ignored?
Thanks in advance!
I think you simplified out the real issue with your sample code if in the "real" situation _foo is false. If B is added as a component either at edit time or at runtime _foo will be true.
I'm sure someone will suggest moving "_foo = true" to Awake(), which would certainly be one way to initialize it correctly.
But I'm curious why this isn't working. In what order are you calling A.Some$$anonymous$$ethod() and B.Some$$anonymous$$ethod()?
B.Some$$anonymous$$ethod is called some time after A.Some$$anonymous$$ethod(). I think calling it the other way round would result in a NullPointerException. The strange thing is that _foo is not accessed anywhere else in my solution (according to the $$anonymous$$onoDevelop "Find references" and "Find in Files" functions). I also tried declaring it as "readonly" which didn't help either. Setting it in Awake() would probably work, but I am still curious why the above doesn't. It's the first declaration/initialization in the class.
I just tested this, and _foo was true. I used the sample code exactly as you posted it, except I changed both Some$$anonymous$$ethod() methods to public so I could call them from a control script.
Like robertbu wrote, the sample code probably simplified out the real issue.
You guys were right. Somehow it works now, even though I don't have the slightest idea why, because I didn't change anything. $$anonymous$$aybe restarting the computer did the trick, or it was due to cosmic noise or the little men inside my computer who randomly change values of computer registers :D . Sorry to have bothered you with this!