Search Unity

MonoBehaviour.Main

Discussion in 'Documentation' started by Baste, Aug 3, 2017.

  1. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,338
    What's the purpose of the Main message?

    Code (csharp):
    1. public class TestScript : MonoBehaviour {
    2.  
    3.     private void Main() {
    4.         Debug.Log("This method gets called, just like Start!");
    5.     }
    6.    
    7. }
    It's not documented, but there's sporadic threads and UA questions about it going back to 2014. Like Start, it can be a coroutine. It seems to be called before Start.

    Is this a very old legacy thing? Is this something that's used internally by Unity?
     
    Xarbrough likes this.
  2. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,998
    At first look, it seems like it could be an artifact of the C++ backend. But no. C++ uses lower-case main (and that doesn't auto run in Unity) and must return int, and isn't a member function. And, now that I think of it, the C# isn't even translated into C++, is it?
     
  3. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,338
    It is if you run IL2CPP, but that's besides the point. The function won't be run as a main function.

    Somewhere in the internal workings of Unity, the engine looks for MonoBehaviours that define a function named "Main", add it to a list of MonoBehaviours with the Main method, and runs that method whenever the object becomes active for the first time, before Start.