关于使用UI按钮更改对象不透明度的问题



在一个空的游戏对象中有三个立方体:redCubeblueCube,&绿色立方体。每个立方体都有自己的标准透明材质:red_matblue_matgreen_mat

将脚本附加到空游戏对象,并将UI按钮(不能使用切换按钮)添加到场景中。单击UI按钮时,所有3个立方体的不透明度都从1f更改为0.5f。再次单击UI按钮时,所有3个立方体的不透明度都将从0.5f变回1f

问题是,当我单击一次UI按钮时,所有立方体的不透明度都会变为0.5f(到目前为止还不错…)。当我再次单击UI按钮时时,所有多维数据集的不透明度会变回1f所有立方体材质都会变回白色,不会恢复到原始颜色。我需要有人告诉我它是如何工作的。

如何在单击UI按钮时仅更改Alpha通道值?我尝试过sharedmaterial/sharedmaterials。但是,它没有起作用。也许我用错了。

using UnityEngine;
public class OpacityController : MonoBehaviour
{
public float opacity = 0.5f; //opacity control
public Component[] renderer; //get all the children renderer component
int i = 0; //toggle the button
void Start()
{
renderer = GetComponentsInChildren<Renderer>();
}
public void OnOpacityButton()
{
Color color1 = GetComponent<Renderer>().material.color;
color1.a = 0.5f;
Color color2 = GetComponent<Renderer>().material.color;
color2.a = 1f;
i++;
if (i % 2 == 1) //toggle the button
{
foreach (Renderer col in renderer)
col.sharedMaterial.color = color1;
} else
{
foreach (Renderer col in renderer)
col.sharedMaterial.color = color2;
}
}
}

如果要更改特定游戏对象的材质,则应使用material而不是sharedmaterial。我建议使用bool而不是int来跟踪切换状态。

我用其他一些改进和注释重构了您的代码:

using UnityEngine;
public class OpacityController : MonoBehaviour
{
public float opacity = 0.5f; //opacity control
public Component[] renderers; //get all the children renderer component
private bool toggle = false;
private void Start()
{
renderers = GetComponentsInChildren<Renderer>();
}
public void OnOpacityButton()
{
// invert the toggle value
toggle = !toggle;
// select the opacity value using the trinary operator
float newOpacity = toggle ? opacity : 1f;
// assign the new opacity to all the renderers
foreach (Renderer renderer in renderers)
{
// copy the current color and assign a new opacity to it.
Color newColor = renderer.material.color; 
newColor.a = newOpacity;
// assign the new color to material rather than sharedmaterial to change only the current material
renderer.material.color = newColor; 
}
}
}

最新更新