# How can I reduce this code?

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);
}


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.

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