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 21:10:41 浏览: 116
可以将重复的代码提取出来,写成一个函数,然后在需要使用的地方调用该函数即可,如下所示:
```
public void ShowPanel(GameObject panel, GameObject image)
{
panel.SetActive(true);
image.SetActive(true);
foreach (Transform child in transform)
{
if (child.gameObject != panel && child.gameObject != image)
{
child.gameObject.SetActive(false);
}
}
}
public void bt2()
{
if (Pan2.activeSelf == false)
{
ShowPanel(Pan2, Imag2);
}
else
{
Pan2.SetActive(false);
Imag2.SetActive(false);
}
}
public void bt3()
{
if (Pan3.activeSelf == false)
{
ShowPanel(Pan3, Imag3);
}
else
{
Pan3.SetActive(false);
Imag3.SetActive(false);
}
}
```
阅读全文