Search Unity

Initialization practices question.

Discussion in 'Scripting' started by StevenJacobs90, Dec 16, 2014.

  1. StevenJacobs90

    StevenJacobs90

    Joined:
    Nov 15, 2014
    Posts:
    12
    Hello, hows everybody doing.

    Im new to programming, and I'm picking it up very fast but some simple questions i can't seem to find solid answers to anywhere on google.

    When declaring a variable, Is it better to give it an initial value even if its going to get a useful value later on? If so, WHY would this be better practice then just leaving it empty?

    Below is an example, should currentHealth be given a initial value of 0, even tho it will be getting the correct value in start? Or is there absolutely no down side doing it this way?

    Code (CSharp):
    1.  
    2. int maxHealth = 300;
    3. int currentHealth;
    4.  
    5. void Start ()
    6. {
    7.     currentHealth = maxHealth;
    8. }
    9.  
    I know this isn't any serious issue, but i don't want to be starting any bad habits.
    so please any help would be appreciated, and thanks for your time!
     
    Last edited: Dec 16, 2014
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Instance variables (and static variables) in a class will have their initial value set to either zero or null. Local-scoped (automatic as we used to call them) variables will not be initialized.

    C# won't let you use a local variable that hasn't been set, either explicitly or by having been passed to a function as an "out" argument.

    Not sure what Javascript will let you get away with, but it's not a bad idea for local variables to actually set them to zero or null.

    If you ever go to an older language and/or compiler environment (C or C++), depending on the compiler warning settings, you can inadvertently run into uninitialized variable problems, so it's not a bad idea to set stuff to zero where you declare it. Some programmers swear by it, others think it just clutters up the code too much.

    Generally it is a good sign that you are thinking of "what can possibly go wrong here?" as you are learning. Keep asking those questions and learn to become the harshest skeptic of your own code. You will learn the most that way and become a better programmer. :)
     
  3. StevenJacobs90

    StevenJacobs90

    Joined:
    Nov 15, 2014
    Posts:
    12
    Awesome, thank you for the advise.. That helped clear things up a bit, basically either way will work but there is no down side to just initializing them, so might as well just to prevent any unknown issues that might come up.