Unity中电量显示和充电状态
2019-05-17 本文已影响0人
吴少年
label显示电量,spBattery电量图标用来切换充电状态。代码如下:
using System.Linq;
using System.Text;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GUIMainSystemInfo : MonoBehaviour
{
// Start is called before the first frame update
[SerializeField]
UILabel labelBattery;
[SerializeField]
UISprite spBattery;
private float batteryLevel = 0;
private float prevBatteryLevel = 0;
private BatteryStatus batteryStatus;
private BatteryStatus prevBatteryStatus;
StringBuilder sb = new StringBuilder();
void Start()
{
if (labelBattery)
{
StartCoroutine("UpdataBattery");
}
}
//更新手机电量
IEnumerator UpdataBattery()
{
while (true)
{
batteryLevel = SystemInfo.batteryLevel;
batteryStatus = SystemInfo.batteryStatus;
if (batteryLevel != prevBatteryLevel || batteryStatus != prevBatteryStatus)
{
prevBatteryLevel = SystemInfo.batteryLevel;
prevBatteryStatus = SystemInfo.batteryStatus;
if (batteryStatus == BatteryStatus.Charging)
{
labelBattery.text = "";
spBattery.spriteName = "btnbatty2";
}else
{
labelBattery.text = GetBatteryLevel();
spBattery.spriteName = "btnbatty";
}
}
yield return new WaitForSeconds(300f);
}
}
//读取手机电量
string GetBatteryLevel()
{
sb.Remove(0, sb.Length);
sb.Append( Mathf.CeilToInt(SystemInfo.batteryLevel*100));
sb.Append("%");
return sb.ToString();
}
}