基本上是一道數學題,想知道有什么好的解法。
問題:我在一行中放置了 25 張影像。我希望影像按順序淡出。也就是說,第一張圖片應該是完全不透明的,最后一張圖片應該是完全透明的。我已將所有這些影像按順序放在一個父項中。
我的解決方案:我只是提供一個固定的數字,它會為 alpha 進行自我迭代。
我在尋找什么:一個公式,以便可以根據存在的影像數量動態更改此“固定”數字。
void Start () {
int color = 10; //my fixed number
foreach (Transform child in transform) {
child.gameObject.GetComponent<Image>().color = new Color32(255, 255, 255, (byte) (255 - color));
color = 10; //iterating for the next child
}
}
uj5u.com熱心網友回復:
簡單地計算步驟怎么樣:
void Start ()
{
if(transform.childCount <= 1)
{
Debug.LogWarning("Requires at least 2 children!");
return;
}
var alphaStep = 1f / (transform.childCount - 1);
var alpha = 1f;
foreach (Transform child in transform)
{
child.GetComponent<Image>().color = new Color(1f, 1f, 1f, alpha);
alpha -= alphaStep;
}
}
或者,如果您想完全控制最大和最小 alpha,您可以使用例如
public float minAlpha = 0f;
public float maxAlpha = 1f;
接著
var alphaStep = 1f / (transform.childCount - 1);
for (var i = 0; i < transform.childCount; i )
{
var factor = i / (transform.childCount - 1);
transform.GetChild(i).GetComponent<Image>().color = new Color(1f, 1f, 1f, Mathf.Lerp(maxAlpha, minAlpha, factor));
}
uj5u.com熱心網友回復:
我會推薦使用陣列來更自由地遍歷你的元素。
有了它,你可以去做類似的事情......(在 SO 中編碼,未經測驗)
Image[] images; //this should reference the array constructed elsewhere where you load the images.
private void Start() {
for (int i = 0; i < images.Length; i ) {
int alpha = 255 - (Mathf.CeilToInt(255 / images.Length) * i 1);
images[i].color = Color32(255,255,255,alpha);}
}
那可能會做你想要的。
順便說一句,不知道為什么你使用 Color32 但使用“浮動”RGBA 將使你擺脫那個 ceil 并給你更多的精度。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/534924.html
標籤:C#unity3d
