Search Unity

GUI code setup help...

Discussion in 'Scripting' started by kingcharizard, Nov 3, 2012.

  1. kingcharizard

    kingcharizard

    Joined:
    Jun 30, 2011
    Posts:
    1,137
    Okay, today I'm going to start creating a GUI for my game, but i cant decide on how to set it up. Here is my general idea.

    I'm going to have a HUD Manager script/class that displays the lives, the score and the level. These 3 variables have to be accessed across multiple scripts. The values inside the variables will be changed depending on gameplay. Here is where I kinda get a little stuck. I know of two basic ways to do this, i am sure there are a few other ways i could achieve this but these are the two I've been considering.

    • Use the GetComponent method
    • Use static variables

    I would assume its safer to use the GetComponent method however its more code to write, But using this method would mean i'd have to have the script attached to the player and not the main camera like I want. To solve this i could use
    Code (csharp):
    1. guiManager = GameObject.Find("Main Camera").GetComponent<GUIManager>();
    but couldn't this cause issues? Or hurt performance? This is for a 2D game so performance isn't a huge concern of mine.

    About the static variables they are risky and I know the more dangerous route to take but would take alot less code, they also wouldn't make me have to attach the script to the player

    Since both methods are capable of dong what i need and could be used, which one should i use? Also I was wondering if there is another way I could have multiple variables able to be accessed across multiple scripts, or is one of these two methods sufficient.
     
    Last edited: Nov 3, 2012
  2. kingcharizard

    kingcharizard

    Joined:
    Jun 30, 2011
    Posts:
    1,137
    I decided on the GetComponent method. I was looking for advice for whats the best practice but oh well i'll go with my gut thats all It really comes down to in the end anyways
     
  3. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    The find statement is generally slow. It's better to just name an object at the top of the script and drag it on with the editor unless your gameobject will be changing during the game, otherwise findObjectWithTag or whatever it is. I personally don't consider statics to be dangerous because you have to name the script where the static resides, so generally there is not really any confusion there. Statics are a good way to avoid duplication that can occur with objects and can save memory. They can be bad if you want multiple objects on purpose with their own data. If they weren't useful, they wouldn't be in almost every language.
     
    Last edited: Nov 4, 2012