/// <summary> /// Updates the values of an already initialized graph with an animation /// </summary> public void UpdateAnimatedBarGraph(List <GraphDataPoint> dataPoints, float yMax, float animationTime) { SourceDataPoints = DataPoints; TargetDataPoints = dataPoints; SourceYMax = YMax; TargetYMax = yMax; AnimationTime = animationTime; AnimationDelay = 0f; AnimationType = GraphAnimationType.Update; }
/// <summary> /// Instantly destroys the whole graph /// </summary> public void ClearGraph(bool stopAnimation = true) { foreach (Transform t in GraphContainer) { Destroy(t.gameObject); } Bars.Clear(); BarLabels.Clear(); if (stopAnimation) { AnimationType = GraphAnimationType.None; } }
void Update() { if (AnimationType != GraphAnimationType.None) { if (AnimationDelay >= AnimationTime) { if (AnimationType == GraphAnimationType.Update) { YMax = TargetYMax; DataPoints = TargetDataPoints; } ShowBarGraph(DataPoints, YMax, YStep, BarSpacing, AxisColor, AxisStepColor, Font); AnimationType = GraphAnimationType.None; if (AnimationCallback != null) { AnimationCallback(); } } else { float r = AnimationDelay / AnimationTime; switch (AnimationType) { case GraphAnimationType.Init: float curValue = MaxValue * r; float curHeight = MaxBarHeight * r; for (int i = 0; i < DataPoints.Count; i++) { float barX = (i + 1) * XStep; float barValue, barHeight; if (DataPoints[i].Value < curValue) { barValue = DataPoints[i].Value; barHeight = (barValue / YMax) * (GraphHeight - YMarginTop); } else { barValue = curValue; barHeight = curHeight; } Vector2 pos = new Vector2(barX, barHeight / 2); Vector2 size = new Vector2(BarWidth, barHeight); RectTransform rect = Bars[i].GetComponent <RectTransform>(); rect.anchoredPosition = pos; rect.sizeDelta = size; float barLabelY = barHeight + FontSize; BarLabels[i].GetComponent <RectTransform>().anchoredPosition = new Vector2(barX, barLabelY); BarLabels[i].text = barValue.ToString("0.0") + "%"; } break; case GraphAnimationType.Update: List <GraphDataPoint> tmpDataPoints = new List <GraphDataPoint>(); float tmpYMax = 0; for (int i = 0; i < TargetDataPoints.Count; i++) { float value = SourceDataPoints[i].Value + (TargetDataPoints[i].Value - SourceDataPoints[i].Value) * r; GraphDataPoint tmpDataPoint = new GraphDataPoint(TargetDataPoints[i].Label, value, TargetDataPoints[i].Color, TargetDataPoints[i].Icons, TargetDataPoints[i].IconTooltipTitles, TargetDataPoints[i].IconTooltipTexts); tmpDataPoints.Add(tmpDataPoint); tmpYMax = SourceYMax + (TargetYMax - SourceYMax) * r; } ShowBarGraph(tmpDataPoints, tmpYMax, YStep, BarSpacing, AxisColor, AxisStepColor, Font, stopAnimation: false); break; } AnimationDelay += Time.deltaTime * AnimationSpeedModifier; } } }
/// <summary> /// Starts the animation that has been previously initialized with InitAnimatedGraph(). Callback gets executed when the animation is done. /// </summary> public void StartAnimation(System.Action callback = null) { AnimationType = GraphAnimationType.Init; AnimationCallback = callback; }