- Home /
Which is better, lots of if-statements or seperate button scripts?
So I'm working on a minigame that is entirely UI driven, I use buttons with gameObject.SetActive to show and hide different menus. Currently those buttons all use the same ButtonScript with
public void OnClick(string text)
{
if (text == "toSub")
{
mainMenu.gameObject.SetActive(false);
subMenu.gameObject.SetActive(true);
}
if (text == "toMain")
{
mainMenu.gameObject.SetActive(true);
subMenu.gameObject.SetActive(false);
}
and so on, which works. I'm just wondering if (and why) it would be better to have seperate button scripts, one for toMain, one for toSub and so on. It's not a giant list or something, will probably cap at 10 or less.
I have seperate scripts for buttons that do completely different things like adding/substracting values etc - would it make sense to put those into the above one single button script with their own ifs, too? I'm tending towards "no", but just for readability reasons.
Bonus question, I feel I should do else if instead of just if on the 2nd+ cases, but I don't see any difference in behaviour, is there one?
Answer by CHPedersen · Feb 03, 2015 at 09:04 AM
It's better to have separate methods for separate button events. :) By the way, it's good that you even think about this stuff - curiosity about these things is what makes a great programmer in the end.
The reason why is found in readability and in performance. For readability and structure, methods should concentrate on doing as few things as possible instead of trying to be catch-alls. When they grow in size, the latter design becomes an antipattern because it grows error-prone.
As for performance, you'd be interested in not having the CPU evaluate conditionals to figure out which button was pressed and therefore, what code to execute. You'd ideally have separate OnClick methods, one for each button, like so:
public void ToMain_OnClick()
{
}
public void ToSub_OnClick()
{
}
... etc
As for the final bonus question, you're perfectly right - in any case where multiple, mutually exclusive conditionals must belong in the same structure, you should always go for if-else if. The reason is that when the condition is mutually exclusive, there is no reason for the CPU to have to evaluate all of the following conditions too.
In your example above, if the input string is equal to "toSub", it cannot at the same time also be equal to "toMain". So if the CPU has already evaluated that it's "toSub" and executed that code, it's a waste of time to also test to see if it's "toMain". "else if" avoids that.
Your answer
Follow this Question
Related Questions
UI element moves down when another UI elements gets too close? 0 Answers
Calling method once 2 Answers
Hide Objects on Higher Plane 0 Answers
Android 3D Touch for Menu 0 Answers