Unity获取电量和充电状态 发表于 2019-05-17 | 分类于 Unity3D | 评论数: | 阅读次数: label显示电量,spBattery电量图标用来切换充电状态。代码如下: 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960using 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(); }} 如果您觉得我的文章对您有所帮助,不妨小额捐助一下,您的鼓励是我长期坚持的动力。 打赏 微信支付 支付宝 本文作者: wumohai 本文链接: https://wumohai.cn/2019/05/17/Unity获取电量和充电状态/ 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!