How do I nest my if, else statement inside my switch case statement. See below…
When I compile I get the following error(4 times for each IF statement)
Assets/_scripts/Shop/unitGameInventory.cs(202,36): error CS0120: An object reference is required to access non-static member `unitGameInventory.MKepler’
Assets/_scripts/Shop/unitGameInventory.cs(204,41): warning CS0162: Unreachable code detected
Assets/_scripts/Shop/unitGameInventory.cs(209,37): warning CS0162: Unreachable code detected
public static bool showAvailableUnits(string unitName)
{
//code here to insert a title for mining ships.
Debug.Log(unitName + " was received by unitGameInventory");
switch (unitName)
{
case "MKepler":
if(MKepler == 1)
{
return true;
break;
}
else
{
return false;
break;
}
case "MMinerva":
if(MMinerva == 1)
{
return true;
break;
}
else
{
return false;
break;
}
case "MFortunate":
if(MFortunate == 1)
{
return true;
break;
}
else
{
return false;
break;
}
case "MCapricorn":
if(MCapricorn == 1)
{
return true;
break;
}
else
{
return false;
break;
}
}
}
since the function is a static function your variables MKepler,MKepler,etc you used in if statements needs to be static variables
I guess since you are returning true false the break has no effect
The error is what @wijesijp said, those need to be static functions
The warning comes from the “break” statements because they can’t be reached since they’re called after return.
But I’m with @OwenReynolds on this one, what are you trying to do?
In general, it’s a bad idea to return out of your code in so many places. Perhaps consider instead setting a variable’s value and then returning that variable at the end
Thank you for the quick responses, you were correct, my variables were not static… for what i’m doing they probably should be but trying to work with them not declared as static.
I re-wrote my method and now i’m just getting one compiler error…
Assets/_scripts/Shop/unitGameInventory.cs(194,20): error CS0161: `unitGameInventory.showAvailableUnits(string)': not all code paths return a value
This error is pointing to the begining of the method.
I’m trying to access this method from another script on an object that runs only when a particular scene is loaded. I’m trying to see if the variables currently have a 1 or a 0.
public int showAvailableUnits(string unitName)
{
//code here to insert a title for mining ships.
Debug.Log(unitName + " was received by unitGameInventory");
switch (unitName)
{
case "MKepler":
return MKepler;
case "MMinerva":
return MMinerva;
case "MFortunate":
return MFortunate;
case "MCapricorn":
return MCapricorn;
}
}