我做了一个右键单击菜单,我想在我将鼠标放在该菜单中的按钮上时使对象更改材料颜色。
这是代码:
Color[] startCo;
public void OnPointerEnter(PointerEventData eventData)
{
GameObject[] objects = GameObject.FindGameObjectsWithTag(myMenu.selected.title);
for (int i = 0; i < startCo.Length; i++)
{
startCo[i] = objects[i].gameObject.GetComponent<MeshRenderer>().material.color;
}
foreach (GameObject obj in objects)
{
obj.gameObject.GetComponent<MeshRenderer>().material.color = Color.red;
}
}
public void OnPointerExit(PointerEventData eventData)
{
GameObject[] objects = GameObject.FindGameObjectsWithTag(myMenu.selected.title);
for (int i = 0; i < objects.Length; i++)
{
objects[i].gameObject.GetComponent<MeshRenderer>().material.color = startCo[i];
}
}
首先要循环,它根本无法工作,但是没有它,当我将鼠标放在按钮上时,它会使材料颜色变红,但不会将其更改回有原始颜色。
我的问题是,有什么更好的方法可以使用 foreach 保存原始颜色?
尝试此版本。它基本上与您的版本完全相同,但请确保在使用颜色阵列之前初始化颜色数组(这可能是您的主要问题)。它还保留了更换颜色的对象列表的副本,如果创建具有匹配标签的新对象或已删除的对象很重要。最后,如果您想在其他地方使用ReplaceColors()
和RestoreColors()
,它添加了一些保障措施,以使其更强大。
GameObject[] objectsWithReplacedColors;
Color[] originalColors;
public void OnPointerEnter(PointerEventData eventData)
{
ReplaceColors(GameObject.FindGameObjectsWithTag(myMenu.selected.title), Color.red);
}
public void OnPointerExit(PointerEventData eventData)
{
RestoreColors();
}
private void ReplaceColors(GameObject[] forObjects, Color withColor)
{
if (objectsWithReplacedColors != null) // if there are already objects with replaced colors, we have to restore those first, or their original color would be lost
RestoreColors();
objectsWithReplacedColors = forObjects;
originalColors = new Color[objectsWithReplacedColors.Length];
for (int i = 0; i < objectsWithReplacedColors.Length; i++)
{
originalColors[i] = objects[i].GetComponent<MeshRenderer>().material.color;
objectsWithReplacedColors[i].GetComponent<MeshRenderer>().material.color = withColor;
}
}
private void RestoreColors()
{
if (objectsWithReplacedColors == null)
return;
for (int i = 0; i < objectsWithReplacedColors.Length; i++)
{
if (objectsWithReplacedColors[i]) // check if the objects still exists (it may have been deleted since its color was replaced)
objectsWithReplacedColors[i].GetComponent<MeshRenderer>().material.color = originalColors[i];
}
objectsWithReplacedColors = null;
originalColors = null;
}
好吧,我的猜测是您每次使用GameObject.FindGameObjectsWithTag
调用这些方法时都在找到对象,而且我很确定未指定FindGameObjectsWithTag
返回的这些对象的顺序调用此方法。这个问题最终为您提供了不同对象的不同原始颜色。我的建议将在Start
中获得objects
,并将颜色分配给数组。然后在OnPointerExit
函数中使用此数组。
您的代码和逻辑对我来说似乎还不错。