- Home /
Constructor in Monobehaviour
I've read that using a constructor on a monobehaviour script is a bad idea. If there was another route to call this script before awake I'm all ears.
I've ran into a situation where I need to set a reference to the data script before anything can access it. Unfortunately some functions were able to access the null data frequently while it resides in the awake function causing errors. Placing a simple reference seems to be the only way right now to get my game to works in a build. For some reason it works just fine in editor. Any alternative suggestions to this issue? I simply need to store a single class before the awake function is called.
Thanks
$$anonymous$$ake a monobehaviour script and set it in the ExecutionOrder (in editor) as the first.
Answer by Bunny83 · Mar 10, 2019 at 10:15 AM
There are generally two solutions for cases like that. The first one is to use the ScriptExecutionOrder and ensure your script is processed first.
Another solution is to use lazy loading which you usually use for singletons.
private Transform m_SomeValue;
public Transform someValue
{
get
{
if (m_SomeValue == null){
\\ initialize m_SomeValue
}
return m_SomeValue;
}
}
Since the question did not include any concrete code we can only suggest a generic solution.
Apart form those solutions I've omitted the most obvious one: exposing the field in the inspector and assigning the reference at edit time.
Currently the issue is caused by a singleton accessing the data before the game is created. I'll work a way to stop that. I was hoping to be done with it and move on but I better not!
Answer by WarmedxMints · Mar 10, 2019 at 09:35 AM
I would suggest that maybe look at your code and see if you can move anything that needs your class doesn't attempt to use it until Start is called.
However, it that is possible for some reason then you can always use the script execution order to ensure that awake call is executed before anything which depends on it.