In Monobehaviour ,if you write parameterless Main() method with void return type then unity will call this main method after OnEnable() and before Start() method. Main is called before the first frame update only if the script instance is enabled.
It also allows access of unity objects in Main() method.
Here is a code snippet,
public class MainMethodExample : MonoBehaviour
{
void Awake ()
{
Debug.Log ("Awake");
}
void OnEnable ()
{
Debug.Log ("OnEnable");
}
void Main ()
{
Debug.Log ("Main");
}
// Use this for initialization
void Start ()
{
Debug.Log ("Start");
}
}
Is it good to use Main() in Monobehaviour as unity is not mentioning it in Unity Documentation?
Main is used in console or windows c# apps as the entry point. I donāt think itās a Unity āmessageā as Visual Studio list the other methods, which is why they probably donāt mention it. Iām sure someone a lot more knowledgeable than I can chip in. Iād be curious if it ran outside the editor the same way.
Itās actually an interesting fact. Though even if itās called by the engine, I wouldnāt rely on it as long as itās not officially documented.
Other than that, a quick test has shown that it runs Main&Start immediately one after the other per instance, so the code in Main could simply run first in Start and itād save that call to Main (unless extensive testing reveals special behaviour).
And if really something like RunAfterAllAwakes / RunBeforeAllStarts is needed, an event would do itās job as well.
Anyway, if anyone has done some more tests regarding that, Iād be interested as well.
Also, that āMainā method could be run as a coroutine. In my opinion, because of previous fact, it calls by the engine, not as entry point of c# program.
In C# Applications the Main method lies in a special class (Program) which is called in order to start the application.
In Unity this entry point of the application is hidden in the engine code (I wished we could have a method for initializing the app also, but it doesnāt exist).
Since this Main() method here is just another āmagic-methodā of a MonoBehaviours, and it can be created for several MonoBehaviours and it is not called first, this has nothing to do with the entry-point-main-method.
I would not use it as others already told. It might be deleted in future versions of Unity and you can achieve everything you need with the other methods you showed.