在最近项目里,每一关卡通关之后,都会增加金币,购买道具则消耗金币,在UI面板会实时显示金币数量的变化。为了增强游戏效果,给金币数值添加了一个动画,实现效果就是可以在指定时间内动态的显示数值变化。
代码也很简单,都不需要注释 ··· ···
public void ShowCoin(Text coinText, int coinValue, int changeCount = 10, float spaceTime = 0.1f)
{
StopAllCoroutines();
StartCoroutine(ShowCoinAni(coinText, coinValue, changeCount, spaceTime));
}
IEnumerator ShowCoinAni(Text coinText, int coinValue, int changeCount, float spaceTime)
{
float lastGoldCount = 0;
if (!string.IsNullOrEmpty(coinText.text))
{
try
{
lastGoldCount = System.Convert.ToInt32(coinText.text);
}
catch(System.Exception e)
{
Debug.Log(e);
}
}
float onceAddCount = 1.0f / changeCount * (coinValue - lastGoldCount);
int i = 0;
while (i < changeCount)
{
i++;
lastGoldCount += onceAddCount;
coinText.text = ((int)lastGoldCount).ToString();
yield return new WaitForSeconds(spaceTime);
}
coinText.text = coinValue.ToString();
}