Unity UGUI Slider顏色過渡
阿新 • • 發佈:2018-11-26
using UnityEngine; using System.Collections; using UnityEngine.UI; public class SliderColor : MonoBehaviour { public Color[] colors = new Color[] { Color.red, Color.yellow, Color.green }; Slider slider; void Start() { slider = GetComponent<Slider>(); slider.fillRect.transform.GetComponent<Image>().color = Color.green; } void Update() { float val = slider.value; val *= (colors.Length - 1); //Mathf.FloorToInt(val) : 向下舍位取整 int startIndex = Mathf.FloorToInt(val); Color color = colors[0]; if (startIndex >= 0) { if (startIndex + 1 < colors.Length) { //提供過渡顏色 float factor = (val - startIndex); color = Color.Lerp(colors[startIndex], colors[startIndex + 1], factor); } else if (startIndex < colors.Length) { //索引為2時為綠色 color = colors[startIndex]; } //當大於陣列長度直接等於綠色 else color = colors[colors.Length - 1]; } color.a = slider.fillRect.transform.GetComponent<Image>().color.a; slider.fillRect.transform.GetComponent<Image>().color = color; } }
轉載自:https://blog.csdn.net/qq_38187606/article/details/79729217