- Home /
Function with multiple if, else if statements.
Is there a problem with having a function that contains multiple if, else if statements in it? I have a function that goes something like:
function broken () {
if (blah blah blah) {
stuff to do;
}
else if (blah blah blah) {
stuff to do;
}
if (blah blah blah) {
stuff to do;
}
else if (blah blah blah) {
stuff to do;
}
}
Only the "print" command in the statements actually works, nothing else does. I don't honestly think it's a problem with this, but I'm out of other ideas. The other stuff that's it's supposed to deals with GUIs. I wrote the first if, else if statment, copied and pasted it 10 times, then changed some of the values so rather than doing the same thing 11 times it does it to 11 different things, but it only prints that it'd doing it, it doesn't actually do it.
Your description is rather confusing. It might help if you post your actual code or sample code with fillers that will actually compile along with the console output so that we may have a better understanding of what is going on.
Answer by robertbu · May 30, 2013 at 06:32 PM
There is no problem with multiple statements, but I don't think you are getting what you think you are getting. It is best until you gain experience to 1) never leave out a bracket, and 2) be very explicit about your indenting. The above can be rewritten as:
if (condition1) {
stuff to do;
}
else {
if (condition2) {
stuff to do;
}
}
if (condition3) {
stuff to do;
}
else {
if (condition4) {
stuff to do;
}
}
Which means you have two separate blocks. If condition1 and condition2 are false nothing happens in the first block. If condition3 and condition4 are false, nothing happens in the second block. What you may want is something like this:
if (condition1) {
//stuff to do;
}
else {
if (condition2) {
//stuff to do;
}
else {
if (condition3) {
//stuff to do;
}
else {
if (condition4) {
//stuff to do;
}
else {
//default stuff to do
}
}
}
}
Often experience programmers will omit the indenting in this kind of if/else chain. Note often this kind of logic is handled by switch()/case statements.
P.S. for some reason the 101/010 has the indentation off a bit. Copy and past it into Mono.
Your answer

Follow this Question
Related Questions
Why is Unity registering my false boolean as true? 1 Answer
Trying to stop or change an if 1 Answer
Display GUI when kill count reaches 5 1 Answer
How to use multiple else if statements C# 2 Answers
Checking the raycast 1 Answer