public GameObject Pan1; public GameObject Imag1; public GameObject Pan2; public GameObject Imag2; public GameObject Pan3; public GameObject Imag3; public GameObject Pan4; public GameObject Imag4; public GameObject Pan5; public GameObject Imag5; public void bt1() { if (Pan1.activeSelf == false) { Pan1.SetActive(true); Imag1.SetActive(true); Pan2.SetActive(false); Imag2.SetActive(false); Pan3.SetActive(false); Imag3.SetActive(false); Pan4.SetActive(false); Imag4.SetActive(false); Pan5.SetActive(false); Imag5.SetActive(false); } else { Pan1.SetActive(false); Imag1.SetActive(false); } } public void bt2() { if (Pan2.activeSelf == false) { Pan2.SetActive(true); Imag2.SetActive(true); Pan1.SetActive(false); Imag1.SetActive(false); Pan3.SetActive(false); Imag3.SetActive(false); Pan4.SetActive(false); Imag4.SetActive(false); Pan5.SetActive(false); Imag5.SetActive(false); } else { Pan2.SetActive(false); Imag2.SetActive(false); } } public void bt3() { if (Pan3.activeSelf == false) { Pan3.SetActive(true); Imag3.SetActive(true); Pan1.SetActive(false); Imag1.SetActive(false); Pan2.SetActive(false); Imag2.SetActive(false); Pan4.SetActive(false); Imag4.SetActive(false); Pan5.SetActive(false); Imag5.SetActive(false); } else { Pan3.SetActive(false); Imag3.SetActive(false); } } unity 用更好的方法整理并减少这段代码
时间: 2024-02-14 18:10:41 浏览: 108
可以使用数组和循环来简化代码,例如:
```
public GameObject[] panels;
public GameObject[] images;
public void ShowPanel(int index)
{
for (int i = 0; i < panels.Length; i++)
{
panels[i].SetActive(i == index);
images[i].SetActive(i == index);
}
}
```
然后在按钮的点击事件中调用 `ShowPanel` 方法并传入对应的索引值,例如:
```
public void bt1()
{
ShowPanel(0);
}
public void bt2()
{
ShowPanel(1);
}
public void bt3()
{
ShowPanel(2);
}
```
这样就可以通过一个方法来控制所有的面板和图片的显示了,代码量也大大减少了。
阅读全文