0
\$\begingroup\$

Could you help me to reduce this code as much as possible?

public GameObject[] TextPage;

public void Skin0()
{
    foreach (GameObject go in TextPage)
    {
        go.SetActive(false);
    }
    TextPage[0].SetActive(true);
}
public void Skin1()
{
    foreach (GameObject go in TextPage)
    {
        go.SetActive(false);
    }
    TextPage[1].SetActive(true);
}
public void Skin2()
{
    foreach (GameObject go in TextPage)
    {
        go.SetActive(false);
    }
    TextPage[2].SetActive(true);
}
\$\endgroup\$
2
\$\begingroup\$

Rather than use a separate method for each entry that you might activate, pass the index of the entry you want to activate:

public void ActivateSkin(int index)
{
    for (int i = 0; i < TextPage.Length; i++)
        TextPage[i].SetActive(i == index);
}

This will iterate over the entire TexpPage array. For each entry, its position is compared to index.
If the position is the same (that is to say, if i == index evaluates to true), then SetActive() will be set to true & if it is not, it will be set to false.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ You posted basically the same code I had drafted, so I ditched my answer & added my explainer text to yours. Edit it as needed. \$\endgroup\$ – Pikalek May 5 at 18:08
  • \$\begingroup\$ Sorry to steal your thunder! \$\endgroup\$ – DMGregory May 5 at 18:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.