byte mag_max = 20;
new byte[] magazine = byte[3] {20,20,20};
byte Get_Best_Mag()
{
byte best_mag = 0;
for ( byte this_mag = 0; this_mag == magazine.Length - 1; this_mag ++ )
{
if ( magazine [this_mag] == mag_max )
{
return this_mag;
}
if ( magazine[this_mag] > magazine[best_mag] )
{
best_mag = this_mag;
}
}
return best_mag;
}
It gives me a "Not all paths return a value" error when I try to do this. I'm probably doing something stupid, but can someone help?
Explain what you’re trying todo…
Are you sure this function gives you the error? Here it is again, with cleaner formatting.
byte Get_Best_Mag() {
byte best_mag = 0;
for ( byte this_mag = 0; this_mag == magazine.Length - 1; this_mag ++ ) {
if ( magazine [this_mag] == mag_max ) {
return this_mag;
}
if ( magazine[this_mag] > magazine[best_mag] ) {
best_mag = this_mag;
}
}
return best_mag;
}
Line 11 is guarantees you that your code returns a value in the end. I don’t see anything wrong with it.
Also:
// Why this:
this_mag == magazine.Length - 1
// and not this:
this_mag < magazine.Length
// ?
It doesn’t return another index other than 0 even when the value at 0 is less than twenty.
I even put a Debug.Log() function in each loop block. BUT, when they should be getting called, I get no messages.
You’re doing this:
for(byte this_mag =0; this_mag == magazine.Length-1; this_mag ++){
While you should be doing this:
for(byte this_mag =0; this_mag <= magazine.Length-1; this_mag ++){
You’re using == comparrison to find when you need to break out of the loop, which is immideately.
To understand what’s going on, remember that a foor loop that looks like this:
for(int i = 0; i < myArray.Length; i++) {
//Code goes here
}
Is essentially a nice way to write this:
int i = 0;
while(i < myArray.Length) {
//Code goes here
i++;
}
If we write what you wrote in that form, it should be easy to see that the loop never runs:
byte this_mag = 0;
while(this_mag == magazine.Length-1) {
//code
this_mag++;
}
Unless your magazine array is exactly 1 long, your loop will never run.
Also note that there’s no reason to use byte as the index in the for-loop. Hell, since you’re on a 32 bit engine, there’s no real reason to use it at all unless you’re planning on writing large amounts of small values to a file, or have some other weird edge case.
^ I thought that’s what the issue was, but wasn’t entirely sure what is it he’s exactly doing…who uses bytes? lol. Please explain why you’re using bytes. I’d love to know.
Because they are the smallest variable aside from bool I think. I worry too much about costing performance for computers I suppose, but hey at least when I make stuff they are optimized out of the box, somewhat at least.
When you operate on bytes like this, they’re implicitly converted to integers - so with the casting and such, you’re actually losing performance.