- Home /
Is it bad coding to have a switch statement with 300 cases in update()?
I want to display a sequence of paragraphs, a new paragraph with every button press. Would it be inefficient to have a switch statement with (maybe) 300 cases in the update function? An example of how it would work:
// a button is pressed that changes a bool variable to true
if bool variable is true
switch (paragraph number variable)
case: paragraph 01
display paragraph 02
change bool variable to false
break
case: paragraph 02
display paragraph 03
change bool variable to false
break
and so on.
Can you try to describe the problem you're trying to solve a bit better? then we might be able to come up with a solution.
Also if I'm guessing correctly here, you want to cycle between text segments, one after the other, based on a key press.
An easy way to achieve this is to have all your text segments in a string array, and have an integer keep track of how far into the conversation you are. Something like this:
void NextTextSegment(){
textField.text = arrayOfParagraphs[currentParagraph];
currentParagraph++;
}
So yeah if you look at it that way, your first proposed solution is pretty inefficient.
Oh yeah i can call functions from Unity (not sure if those are the right terms). Hah i've got a long way to go.
Answer by CarterG81 · Feb 26, 2017 at 11:30 PM
Yea, definitely.
There are nearly always better ways to code "300 cases" than using a switch. Most programmers don't use switches larger than 5-10.
Part of what makes a good programmer is their ability to write readable code & code that is easily extendable. Having to sift through hundreds of conditionals is not user friendly.
If you're just iterating through paragraphs, you should simply use a loop of some kind. Iterate through an array, List, dictionary, whatever. There are usually better ways than enormous switch statements, like making a generic method or approaching the problem in a completely different way. Just as NecrosDk suggests.
If you tell more details, like how you write your content, we could better help answer the question. But really the answer is "Yes. It is bad coding." However it does work - it's just not a good way to code.
Well i want to make a working prototype with paragraphs showing up in sequence before attempting to make a text adventure game. Perhaps with branching paths that might loop back to the main story thread. Although looking at the problem now I think I'm going to have to study program$$anonymous$$g a bit more.