- Home /
C# Array Issue
Pretty simple code, really don't understand why I can't reassign arrays in these circumstances (error CS0165: Use of unassigned local variable `trapToChoose'):
int[] trapToChoose;
switch (gameManagerScript.landscape)
{
case "City":
if (floorNumber < 51)
{
trapToChoose = new int[] {20, 50, 70, 100, 100, 100};
}
else if (floorNumber > 50 && floorNumber < 101)
{
trapToChoose = new int[] {20, 50, 70, 100, 100, 100};
}
else if (floorNumber > 100)
{
trapToChoose = new int[] {20, 50, 70, 100, 100, 100};
}
break;
case "Forest":
if (floorNumber < 51)
{
trapToChoose = new int[] {20, 50, 70, 100, 100, 100};
}
else if (floorNumber > 50 && floorNumber < 101)
{
trapToChoose = new int[] {20, 50, 70, 100, 100, 100};
}
else if (floorNumber > 100)
{
trapToChoose = new int[] {20, 50, 70, 100, 100, 100};
}
break;
default:
print (" PopTrap Script Error");
trapToChoose = new int[] {0, 0, 0, 0, 0, 0};
break;
}
randomPicker = (int) Mathf.Round(Random.Range(0, 100));
if (randomPicker <= trapToChoose[0])
chosenTrap = 0;
else if (randomPicker > trapToChoose[0] && randomPicker <= trapToChoose[1])
chosenTrap = 1;
Also, would love to know why I am forced to use the {} for the If statement inside a switch (embedded statement error)
Answer by robertbu · Jul 13, 2014 at 03:25 PM
The problem is that the compiler sees a way through your code that has you using 'trapToChoose' without initializing it. In this case, the problem happens if 'landscape' is something other than 'City'. 'trapToChoose' is not initialized, and therefore your use of it on line 14 is an error.
Note I did not get an error when I removed the {} from the 'if' statement.
That is just a part of the code. There are 6 cases, finalizing with the "default" one.
Okay, but what happens if the switch is "City" and the floor is > 51?
...and as far as forced braces go, I don't recall ever having to use them for a single-line if-statement; maybe that's just happening because of the array error, not sure.
Put all the code of that method, so there are no misconceptions. Hopefully you can see what I can't
Your answer
Follow this Question
Related Questions
C# SetActive GameObject Array 2 Answers
Unity 3 GD HotShot-Tutorial Problem with an C#-Array 1 Answer
Saving 30 bools in an array possible? 2 Answers
Switching Weapons (C#) 2 Answers
Array iteration problem 1 Answer