Search Unity

Concept of Main or single code entry point

Discussion in 'Scripting' started by eco_bach, Sep 23, 2014.

  1. eco_bach

    eco_bach

    Joined:
    Jul 8, 2013
    Posts:
    1,601
    Coming from a Java and Actionscript background I am accustomed to using a 'Main' class or something similar as the single code entry point for initializing my application. Is this idea no longer relevant in the Unity world?
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Not really, no. Unity is based on a component-based architecture approach. Components in Unity are classes that derive from MonoBehaviour, and have a number of magic methods (which they call "Messages") that are found by name and invoked automatically by the Unity runtime, for all active MonoBehaviours attached to active GameObjects.

    Each component is generally responsible for initializing itself, which can happen in any or all of several stages:
    1. The object's public properties are set (deserialized) with the values set in the Unity editor.
    2. The object's Awake() method is invoked.
    3. The object's Start() method is invoked.
    So, in most cases, you can do what you need there. When you have some sort of global game state you want to initialize, well, make a MonoBehaviour for that too, and stick it on an empty GameObject in your scene.
     
  3. sluice

    sluice

    Joined:
    Jan 31, 2014
    Posts:
    416
    I am also from an ActionScript background.

    You can attach a script to an empty GameObject.
    and/or
    Use make a singleton class called whatever suits you: GameManager/GodClass/Main

    I always do a GameManager class that keeps tracks of important info, objects and states of the game.
     
    MrGuardianX likes this.
  4. Cygon4

    Cygon4

    Joined:
    Sep 17, 2012
    Posts:
    382
    In Unity, there's a start scene which gets loaded first. However, there can be any number of GameObjects in it and any number of Components (including scripts) attached to them. Their initialization order is undefined, though Unity allows you to customize it -> search for "Script Execution Order". For portability and ease-of-use of your scripts, it's preferable to design them to not depend on any specific initialization order.

    If you have a bit of background in Java, you can use IoC containers in Unity (within limits -- no constructor injection, for example).

    Most projects I've seen however just use the singleton pattern or static variables. While pretty sloppy, Unity's design isn't really supportive of decoupling and interface-based design anyway, so you'll only lose a bit of testability.