我有4个按钮。每个按钮都会打开游戏对象并关闭其他三个按钮。
有没有比我下面更好的方法。
public void Button1() {
gameObject1.SetActive(true);
gameObject2.SetActive(false);
gameObject3.SetActive(false);
gameObject4.SetActive(false);
}
public void Button2()
{
gameObject1.SetActive(false);
gameObject2.SetActive(true);
gameObject3.SetActive(false);
gameObject4.SetActive(false);
}
public void Button3()
{
gameObject1.SetActive(false);
gameObject2.SetActive(false);
gameObject3.SetActive(true);
gameObject4.SetActive(false);
}
public void Button4()
{
gameObject1.SetActive(false);
gameObject2.SetActive(false);
gameObject3.SetActive(false);
gameObject4.SetActive(true);
}
答案 0 :(得分:2)
我会这么说,是的。创建按钮游戏对象的数组并循环浏览该列表。我假设您在编辑器中设置了按钮关联:
(未测试的)
using System.Collections.Generic;
public class YourClass : MonoBehavour
{
public GameObject gameObject1;
public GameObject gameObject2;
public GameObject gameObject3;
public GameObject gameObject4;
private List<GameObject> _buttons = null;
void Start()
{
_buttons = new List<GameObject>();
_buttons.Add(gameObject1);
_buttons.Add(gameObject2);
_buttons.Add(gameObject3);
_buttons.Add(gameObject4);
// Other stuff
}
public void Button1()
{
TurnOnButton(0);
}
public void Button2()
{
TurnOnButton(1);
}
public void Button3()
{
TurnOnButton(2);
}
public void Button4()
{
TurnOnButton(3);
}
private void TurnOnButton(int buttonNumber)
{
for (int i = 0; i < _buttons.Count(); i++) {
_buttons[i].SetActive(i == buttonNumber);
}
}