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:11:18 浏览: 71
XGUI Unity3d 读取数据库 向gameobject添加数据
可以使用数组和循环来简化这段代码,如下所示:
```
public GameObject[] panels;
public GameObject[] images;
public void ShowPanel(int index)
{
for (int i = 0; i < panels.Length; i++)
{
if (i == index)
{
panels[i].SetActive(true);
images[i].SetActive(true);
}
else
{
panels[i].SetActive(false);
images[i].SetActive(false);
}
}
}
```
在这里,我们使用了两个数组来存储面板和图像的引用,并创建了一个函数来显示指定的面板和图像。当函数被调用时,它会遍历所有的面板和图像,如果当前索引等于传递的索引,则设置面板和图像为活动状态,否则将它们设置为非活动状态。这种方法可以大大减少代码行数,使代码更加简洁。
阅读全文