public GenericDictionary<Button, GameObject> buttonPrefabMap; private GameObject currentPrefab; private bool isPrefabLoaded = false; public Outline[] outlines; // 所有按钮的外轮廓组件 public GameObject CHild;//子物体 public void LoadPrefab(Button button) { if (isPrefabLoaded) //panels[i].activeSelf == false { Destroy(currentPrefab); isPrefabLoaded = false; SetOutline(false); //button.GetComponent<Outline>().enabled = false; // 取消外轮廓 return; } // 获取按钮对应的预制体 GameObject prefab = buttonPrefabMap[button];//GameObject // 销毁当前加载的预制体 Destroy(currentPrefab); // 加载新的预制体 currentPrefab = Instantiate(prefab,CHild.transform); isPrefabLoaded = true; SetOutline(true, button); // 添加当前按钮的外轮廓 //button.GetComponent<Outline>().enabled = true; // 添加外轮廓 } private void SetOutline(bool value, Button button = null) { foreach (Outline outline in outlines) { outline.enabled = false; } if (value && button != null) { button.GetComponent<Outline>().enabled = true; // 自动取消其他按钮的轮廓 foreach (Button otherButton in buttonPrefabMap.Keys) { if (otherButton != button && otherButton.GetComponent<Outline>().enabled) { otherButton.GetComponent<Outline>().enabled = false; } } } } unity 修改代码 点击按钮1加载模型 轮廓显示 点击按钮2加载新模型 自动取消按钮1的轮廓 按钮2的轮廓显示 不用bool的方式
时间: 2024-02-10 22:13:29 浏览: 117
Unity3D中通过代码自动为GameObject添加相应的组件1
可以使用一个记录当前选中按钮的变量,来判断是否需要取消前一个按钮的轮廓并添加当前按钮的轮廓。修改后的代码如下:
```csharp
public GenericDictionary<Button, GameObject> buttonPrefabMap;
private GameObject currentPrefab;
private Button currentButton; //记录当前选中的按钮
public Outline[] outlines;
public GameObject CHild;
public void LoadPrefab(Button button)
{
if (currentButton == button)
{
Destroy(currentPrefab);
currentButton = null;
SetOutline(false);
return;
}
GameObject prefab = buttonPrefabMap[button];
Destroy(currentPrefab);
currentPrefab = Instantiate(prefab, CHild.transform);
currentButton = button;
SetOutline(true);
}
private void SetOutline(bool value)
{
foreach (Outline outline in outlines)
{
outline.enabled = false;
}
if (value && currentButton != null)
{
currentButton.GetComponent<Outline>().enabled = true;
foreach (Button otherButton in buttonPrefabMap.Keys)
{
if (otherButton != currentButton && otherButton.GetComponent<Outline>().enabled)
{
otherButton.GetComponent<Outline>().enabled = false;
}
}
}
}
```
这样,当点击同一个按钮时,会取消该按钮的轮廓并销毁已加载的预制体;当点击不同的按钮时,会取消前一个按钮的轮廓并加载新的预制体和添加当前按钮的轮廓。
阅读全文