Best way to simplify this code
Whats the best way to simplify this switch character script? The start function is used to enable the character that was selected in the previous game with player prefs. The avatar() methods are connected to a button. When the character button is clicked all characters are turned off except the selected character. Then it sets the player prefs value to its respective player index. I'm sure there's a better way of doing this. Any code that gets the same result will work. Thanks.
public class SwitchCharacterScript : MonoBehaviour {
public GameObject avatar1, avatar2, avatarN, ...;
void Start ()
{
if (GameSaves.currentSkinIndex == 1)
avatar1.gameObject.SetActive(true);
else
avatar1.gameObject.SetActive(false);
if (GameSaves.currentSkinIndex == 2)
avatar2.gameObject.SetActive(true);
else
avatar2.gameObject.SetActive(false);
...
}
public void Avatar1()
{
avatar1.gameObject.SetActive(true);
avatar2.gameObject.SetActive(false);
...
GameSaves.currentSkinIndex = 1;
GameSaves.Instance.Save();
}
...
public void AvatarN()
{
avatar1.gameObject.SetActive(false);
avatar2.gameObject.SetActive(false);
...
avatarN.gameObject.SetActive(true);
...
GameSaves.currentSkinIndex = 3;
GameSaves.Instance.Save();
}
Answer by Cornelis-de-Jager · Feb 19, 2019 at 09:26 PM
When selecting a button I believe you are able to assign an integer to the button when calling a function. Or at the very least its easy to make it do it, probally make another Unity question if you do need help with that, as for the simplified script:
public GameObject[] avatars;
void Start () {
// Skin index starts at 1 - array starts at 0, so we subtract one
SelectAvatar(GameSaves.currentSkinIndex - 1);
}
public void SelectAvatar (int selection) {
for (int i = 0; i < avatars.Count(); i++){
if (i == selection) {
avatars[i].SetActive(true);
} else {
avatars[i].SetActive(false);
}
}
// Here we add one again for the diff in skin index
GameSaves.currentSkinIndex = selection + 1;
GameSaves.Instance.Save();
}
why iterate array on each select avatar, why not do it just on start and, when select only disable the last (the only who is visible)?
public GameObject[] avatars;
void Start () {
//disable all
foreach (GameObject avatar in avatars)
avatar.SetActive(false);
//enable first
SelectAvatar(GameSaves.currentSkinIndex - 1);
}
public void SelectAvatar (int selection) {
//disable the last
avatars[GameSaves.currentSkinIndex-1].SetActive(false);
// enable current
avatars[selection].SetActive(true);
GameSaves.currentSkinIndex = selection + 1;
GameSaves.Instance.Save();
}
Your answer
Follow this Question
Related Questions
Using downloaded image as UI Image's source image? 1 Answer
Pause menu done exactly according to tutorial doesen't work 2 Answers
Unity 5.3 UI Button wont set Select state via script after the parent has been set inactive 0 Answers
Is there a way I can make one script for all my buttons in my game? 1 Answer
Updating UI Text of an existing element in a list. 0 Answers