Search Unity

Bug Strange temp variable problem

Discussion in 'Scripting' started by TiggyFairy, Apr 17, 2022.

  1. TiggyFairy

    TiggyFairy

    Joined:
    Dec 22, 2019
    Posts:
    506
    Can anyone explain to me what's going on here? I'm just totally lost. I have a whole list of eight
    buttonNumber == 1
    entries just like this, and only the first one has a
    Use of unassigned local variable 'tileValue'
    error. This has happened before, but as you can see it has no problem with two other identical values. Removing the
    else
    doesn't cause the second one to show an error, BUT removing the line causes the next one to error. Changing the name doesn't help.

    huh.PNG

    hug.PNG
     
  2. passerbycmc

    passerbycmc

    Joined:
    Feb 12, 2015
    Posts:
    1,741
    if you want to use tileValue like this give it a value first
    int tileValue = 0;
     
  3. TiggyFairy

    TiggyFairy

    Joined:
    Dec 22, 2019
    Posts:
    506
    Oh oops. I didn't notice I didn't do that because it wasn't erroring on the first line. Thanks a lot, I feel really stupid now.
     
  4. Peeling

    Peeling

    Joined:
    Nov 10, 2013
    Posts:
    443
    FYI the first line isn't an error. It's okay to declare a variable without initialising it, so long as the compiler can work out that it will be initialised before first being used.
     
  5. passerbycmc

    passerbycmc

    Joined:
    Feb 12, 2015
    Posts:
    1,741
    yeah what at @Peeling said, for example if it was a if else statement and both branches assigned to it, it would be fine not to initialize it first, since the compiler knows it will be done before it gets used. but since it was a if/if else compiler sees its possible it might not be initialized before use.
     
  6. TiggyFairy

    TiggyFairy

    Joined:
    Dec 22, 2019
    Posts:
    506
    Thank you, that's quite interesting