如何更改 children 的 alpha
How to change alpha of children
在 Unity 中我有一个游戏 object 作为 parent 和两个 child text-objects 作为 children。还有一张图child-object(一共三个children)
现在我想更改 game-object 的三个 children 的 alpha。我如何以编程方式完成此操作?
我有这段代码,但它不适用于文本和 image-objects:
public void setAlpha(float alpha) {
SpriteRenderer[] children = GetComponentsInChildren<SpriteRenderer>();
Color newColor;
foreach(SpriteRenderer child in children) {
newColor = child.color;
newColor.a = alpha;
child.color = newColor;
}
}
如果您使用 SpriteRenderer
,您的代码将有效。
您可以通过更改 Text
和 Image
颜色 属性 的 Alpha 通道来实现,这与您所做的非常相似:
public void setAlpha(float alpha) {
Color newColor;
Image[] childrenImg = GetComponentsInChildren<Image>();
foreach(Image img in childrenImg) {
newColor = img.color;
newColor.a = alpha;
img.color = newColor;
}
Text[] childrenText = GetComponentsInChildren<Text>();
foreach(Text text in childrenText) {
newColor = text.color;
newColor.a = alpha;
text.color = newColor;
}
}
不要忘记在脚本顶部包含 using UnityEngine.UI;
,因为 Text
和 Image
是 UI 个元素。
无需重新发明轮子。
UI elements 有一个现成的组件 CanvasGroup:
它具有应用于所有子项的 Alpha 属性。
在 Unity 中我有一个游戏 object 作为 parent 和两个 child text-objects 作为 children。还有一张图child-object(一共三个children)
现在我想更改 game-object 的三个 children 的 alpha。我如何以编程方式完成此操作?
我有这段代码,但它不适用于文本和 image-objects:
public void setAlpha(float alpha) {
SpriteRenderer[] children = GetComponentsInChildren<SpriteRenderer>();
Color newColor;
foreach(SpriteRenderer child in children) {
newColor = child.color;
newColor.a = alpha;
child.color = newColor;
}
}
如果您使用 SpriteRenderer
,您的代码将有效。
您可以通过更改 Text
和 Image
颜色 属性 的 Alpha 通道来实现,这与您所做的非常相似:
public void setAlpha(float alpha) {
Color newColor;
Image[] childrenImg = GetComponentsInChildren<Image>();
foreach(Image img in childrenImg) {
newColor = img.color;
newColor.a = alpha;
img.color = newColor;
}
Text[] childrenText = GetComponentsInChildren<Text>();
foreach(Text text in childrenText) {
newColor = text.color;
newColor.a = alpha;
text.color = newColor;
}
}
不要忘记在脚本顶部包含 using UnityEngine.UI;
,因为 Text
和 Image
是 UI 个元素。
无需重新发明轮子。 UI elements 有一个现成的组件 CanvasGroup:
它具有应用于所有子项的 Alpha 属性。