How can I simplify this code?

Hi All
I was wondering if you guys can help me simplify my code(I am a beginner of programming.)
what I want to achieve here is accordingly.

[problem]
I wrote a switch statement but they are pretty long, and if I add more characters to select, it is not efficient to add like that.
basically, if a certain character is on, other 3 or more character will be setActive to false at the same time with a few lines of code. by the way, these characters are a child object of the parent object.

Thank you

[character select UI for mobile]

  1. I put 4 buttons UI in Unity for selecting characters
  2. each button has ID numbers
  3. if a certain character is on, other characters are off.
public class characterManager : MonoBehaviour
{
    public GameObject[] newCharacter;

    void Start()
    {
        newCharacter = GetComponentsInChildren<GameObject>();
    }

    // Update is called once per frame
    void Update()
    {
      switch(characterSelect.playerNumber)
        {
         

            case 0:
                newCharacter[characterSelect.playerNumber].SetActive(true);
                newCharacter[1].SetActive(false);
                newCharacter[2].SetActive(false);
                newCharacter[3].SetActive(false);

                break;
            case 1:
                newCharacter[characterSelect.playerNumber].SetActive(true);
                newCharacter[0].SetActive(false);
                newCharacter[2].SetActive(false);
                newCharacter[3].SetActive(false);

                break;
            case 2:
                newCharacter[characterSelect.playerNumber].SetActive(true);
                newCharacter[0].SetActive(false);
                newCharacter[1].SetActive(false);
                newCharacter[3].SetActive(false);

                break;
            case 3:
                newCharacter[characterSelect.playerNumber].SetActive(true);
                newCharacter[0].SetActive(false);
                newCharacter[1].SetActive(false);
                newCharacter[2].SetActive(false);

                break;
               
        }
    }

Seems like you want a for loop.

void Update()
{
    for(int i = 0; i < newCharacter.Length; i++) // Starting from 0, loop through each element of the array
    {
        newCharacter[i].SetActive(i == characterSelect.playerNumber); // set the object active only if i == our selected number.
    }
}
1 Like

OMG THANK YOU SOOOOOOO MUCH WallaceT_MFM! You are so genius!
I really appreciate it so much. Wow, I really need to practice until I can be close to your level :slight_smile:
from now on, I will use this great code to my UI all the time. Thank you from Japan!!!

2 Likes