I understand using constructor in a MonoBehavior is a big no-no as Unity has the very bad habit of calling it randomly whenever it feels like it.
However, I need to create subobjects contained within that MonoBehavior when it’s first created.
Of course, those subobjects are serialized and should not be recreated when loaded.
I’ve look at Start() and Awake() and both are not called when I would like it - when the game is running -, and I can’t find a “OnCreate” method. Someone have an idea?
I believe I can help, but due to the internet I am currently using, I can’t tell if this has already been said in the comment section.
Anyway, let me make this clear: When you write a script, all you are doing is defining behaviour. The script (as a component) is never “created” before the game is run. This means that your theoretical
OnCreated is the exact same as the already existing
I believe what you are looking for is some sort of dependancy system.
Since you have not stated the context in which you need the dependancy, I will explain both methods of achieving it:
If you have a scirpt that requires another script or another component to be part of the same object, but you can’t be sure that it always gets added, or it just makes it easier, then you can use
[RequreComponent(Type)]. This will automatically attach the component of type
Type when this script is added. This works both when using
AddComponent in a scirpt or when adding the script to a object
If you have a component (or anything really) and you want it to be dependant on some sort of heiarchy (or really anything), you can write a custom
Editor for you script. This will allow you to quite literally do anything when the script is added to a
GameObject. Note that this will not work in a build, so you can only use it while in editor.
Last but not least you really should just do all this in
Awake. Makes things easy and it does work.
Awake btw is called inside the
Instantiate function, so it gets called before anything else. This is where you make defaults
Hope this helps,