Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

where to initialize static classes?

Discussion in 'Scripting' started by AstralProjection, May 20, 2013.

  1. AstralProjection

    AstralProjection

    Joined:
    Feb 12, 2013
    Posts:
    11
    Got a few static classes with no state or dependencies that are very useful to call from anywhere. What's the best way to call their Initialize() functions at game start?
     
  2. cdevl

    cdevl

    Joined:
    Apr 10, 2013
    Posts:
    180
    I always have a GameControl Monobehaviour attached either to a main camera or a dummy GameObject (usually called Game). Most initializations would run from the Start method of that Monobehavior. There are other ways to do it I guess. But that is the one I use.
     
  3. AstralProjection

    AstralProjection

    Joined:
    Feb 12, 2013
    Posts:
    11
    Ahh ok thanks cdevl. Was thinking it would require a game object.
     
  4. cdevl

    cdevl

    Joined:
    Apr 10, 2013
    Posts:
    180
    Just make sure that if that GameControl GameObject doesn't do any updates (mine actually does; it controls global actions - like Pause) - delete the Update method from your code so Unity doesn't call it each frame. I actually asked that question here on the forum. If you get rid of an Update method then there is no per-frame overhead.
     
  5. cdevl

    cdevl

    Joined:
    Apr 10, 2013
    Posts:
    180
    You may also make sure that if you are loading a new scene and destroying GameControl that you don't reinit your statics (or just make sure that your init(s) are re-enterable).
     
  6. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,519
    It does not require a GameObject.

    For what you describe (no state, no dependencies, just provides functions) making the functions themselves static sounds like it would suit best.
     
  7. exiguous

    exiguous

    Joined:
    Nov 21, 2010
    Posts:
    1,749
    a static constructor is guaranteed to (implicetly, no need to call explicitely) run before any access to the static parts of a class. so call initialize there.

    if other gameobjects rely on the data in your class this can cause problems when you don't consider script execution order.
     
    Last edited: May 21, 2013