本文共 22554 字,大约阅读时间需要 75 分钟。
using UnityEngine;using System.Collections;using System.IO;using System.Text;using System;using System.Security.Cryptography;public class MD5Utility{ public static string FileMd5(string file) { try { FileStream fs = new FileStream(file, FileMode.Open); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(fs); fs.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb.ToString(); } catch (Exception ex) { throw new Exception("md5file() fail, error:" + ex.Message); } } public static string StringMd5(string source) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] data = System.Text.Encoding.UTF8.GetBytes(source); byte[] md5Data = md5.ComputeHash(data, 0, data.Length); md5.Clear(); string destString = ""; for (int i = 0; i < md5Data.Length; i++) { destString += System.Convert.ToString(md5Data[i], 16).PadLeft(2, '0'); } destString = destString.PadLeft(32, '0'); return destString; } public static string ByteMd5(byte[] bt) { try { System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(bt); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb.ToString(); } catch (Exception ex) { throw new Exception("md5file() fail, error:" + ex.Message); } }}
using UnityEngine;using System.Collections;using DG.Tweening;using UnityEngine.UI;public static class DOTweenXExtension{ public static void DOFloatText(this Text tweenText, float from, float to, float duration = 0.2f, TweenCallback action = null) { if (tweenText == null) return; tweenText.DOKill(); Tween tween = DOVirtual.Float(from, to, duration, x => { tweenText.text = ((long)x).ToString(); }); if (action != null) tween.OnComplete(action); } public static Tweener DORotateX(this Transform target, float endValue, float duration, RotateMode mode = RotateMode.Fast) { return target.DORotate(new Vector3(endValue, target.eulerAngles.y, target.eulerAngles.z), duration, mode); } public static Tweener DORotateY(this Transform target, float endValue, float duration, RotateMode mode = RotateMode.Fast) { return target.DORotate(new Vector3(target.eulerAngles.x, endValue, target.eulerAngles.z), duration, mode); } public static Tweener DORotateZ(this Transform target, float endValue, float duration, RotateMode mode = RotateMode.Fast) { return target.DORotate(new Vector3(target.eulerAngles.x, target.eulerAngles.y, endValue), duration, mode); } public static Tweener DOLocalRotateX(this Transform target, float endValue, float duration, RotateMode mode = RotateMode.Fast) { return target.DORotate(new Vector3(endValue, target.localEulerAngles.y, target.localEulerAngles.z), duration, mode); } public static Tweener DOLocalRotateY(this Transform target, float endValue, float duration, RotateMode mode = RotateMode.Fast) { return target.DORotate(new Vector3(target.localEulerAngles.x, endValue, target.localEulerAngles.z), duration, mode); } public static Tweener DOLocalRotateZ(this Transform target, float endValue, float duration, RotateMode mode = RotateMode.Fast) { return target.DORotate(new Vector3(target.localEulerAngles.x, target.localEulerAngles.y, endValue), duration, mode); } //延迟激活或禁用 public static Tweener DOSetActive(this GameObject target, bool value, float duration) { float dv = 0.0f; return DOTween.To(() => dv, x => dv = x, 1.0f, duration).OnComplete(() => { if (target && !target.IsNull()) target.SetActive(value); }); } public static int DOKill(this GameObject target, bool complete = false) { return DOTween.Kill(target, complete); }}
using System;using System.Collections.Generic;using UnityEngine;public class LocalCacheUtility{ [Serializable] public class SaveData { public int time; public string data; public override string ToString() { return string.Format("SaveData[ time={0} data={1} ]", time, data); } } public static void SaveFloat(string key, float value) { PlayerPrefs.SetFloat(key, value); } public static float GetFloat(string key) { return PlayerPrefs.GetFloat(key); } public static void SaveInt(string key, int value) { PlayerPrefs.SetInt(key, value); } public static int GetInt(string key) { return PlayerPrefs.GetInt(key); } public static void SaveString(string key, string value) { PlayerPrefs.SetString(key, value); } public static string GetString(string key) { return PlayerPrefs.GetString(key); } public static bool HasKey(string key) { return PlayerPrefs.HasKey(key); } public static void DeleteKey(string key) { PlayerPrefs.DeleteKey(key); } public static void DeleteAll() { PlayerPrefs.DeleteAll(); } public static void SaveAll() { PlayerPrefs.Save(); } ////// 获取时间戳 /// ///static int GetTimeStamp() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return (int)ts.TotalSeconds; } static DateTime StampToDateTime(string timeStamp) { DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = long.Parse(timeStamp + "0000000"); TimeSpan toNow = new TimeSpan(lTime); return dateTimeStart.Add(toNow); } /// /// 保存存在一定时间的本地数据 /// /// /// public static void SaveTimeData(string key, string data, int seconds) { SaveData sdata = new SaveData(); sdata.data = data; sdata.time = GetTimeStamp() + seconds; string json = JsonUtility.ToJson(sdata); SaveString(key, json); //Debug.Log(StampToDateTime(sdata.time.ToString())); } public static SaveData GetTimeData(string key) { string json = GetString(key); if (string.IsNullOrEmpty(json)) return null; try { SaveData saveData = JsonUtility.FromJson(json); return saveData; } catch (Exception e) { Debug.LogError("LocalCacheUtility::GetTimeData() " + e.ToString()); } return null; } /// /// 将缓存保存天数 /// /// /// public static void SaveDay(string key, int day) { SaveTimeData(key, "", (Mathf.Clamp(day - 1, 0, day)) * 86400); } //天数 public static bool GetDay(string key) { int now = GetTimeStamp(); SaveData sdata = GetTimeData(key); return sdata != null && sdata.time > now; } //是否为同一天 public static bool GetSameDay(string key) { SaveData sdata = GetTimeData(key); if (sdata == null) return false; DateTime dateTime = StampToDateTime(sdata.time.ToString()); DateTime dateTimeNow = StampToDateTime(GetTimeStamp().ToString()); return dateTimeNow.Day == dateTime.Day; }}
using UnityEngine;using System.Collections;using System.IO;using System.Text;using System;public class XFileUtility{ public static Sprite ReadStreamingImg(string path, out string error) { error = string.Empty; Sprite sprite = null; Texture2D texture = null;#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_IOS try { byte[] bytes = File.ReadAllBytes(path); texture = new Texture2D(1, 1); texture.LoadImage(bytes); sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero); } catch (System.Exception e) { error = e.ToString(); }#elif UNITY_ANDROID WWW www = new WWW(path); while (!www.isDone) System.Threading.Thread.Sleep(5); error = www.error; if (string.IsNullOrEmpty(error)) { texture = www.texture; sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero); www.Dispose(); }#endif return sprite; } public static string ReadStreamingFile(string path, out string error) { error = string.Empty; string data = string.Empty; #if UNITY_EDITOR || UNITY_STANDALONE || UNITY_IOS try { data = File.ReadAllText(path); } catch (System.Exception e) { error = e.ToString(); }#elif UNITY_ANDROID WWW www = new WWW(path); while (!www.isDone) System.Threading.Thread.Sleep(5); error = www.error; if (string.IsNullOrEmpty(error)) { data = www.text; www.Dispose(); }#endif return data; } public static AssetBundle ReadStreamingAssetBundle(string path, out string error) { error = string.Empty; AssetBundle data = null;#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_IOS try { if (File.Exists(path)) data = AssetBundle.LoadFromFile(path); else error = "file not exist! " + path; } catch (System.Exception e) { error = e.ToString(); }#elif UNITY_ANDROID WWW www = new WWW(path); while (!www.isDone) System.Threading.Thread.Sleep(5); error = www.error; if (string.IsNullOrEmpty(error)) { data = www.assetBundle; www.Dispose(); }#endif return data; } public static Sprite ReadStreamingImgEx(string fileName, out string error) { if (string.IsNullOrEmpty(fileName)) { error = "path is error"; return null; } return ReadStreamingImg(Path.Combine(AssetManagement.AssetDefine.streamingAssetsPath, fileName), out error); } public static AssetBundle ReadStreamingAssetBundleEx(string fileName, out string error) { return ReadStreamingAssetBundle(Path.Combine(AssetManagement.AssetDefine.streamingAssetsPath, fileName), out error); } public static AssetBundle ReadPersistentAssetBundle(string fileName, out string error) { error = string.Empty; string path = Path.Combine(AssetManagement.AssetDefine.ExternalSDCardsPath, fileName); if (File.Exists(path)) { try { return AssetBundle.LoadFromFile(path); } catch (Exception ex) { error = ex.ToString() + path; } } error = "file not exist! " + path; return null; } public static void WriteText(string path, string data) { if (File.Exists(path)) File.Delete(path); else { string parent = Path.GetDirectoryName(path); if (!Directory.Exists(parent)) Directory.CreateDirectory(parent); } File.WriteAllText(path, data); } public static void WriteBytes(string path, byte[] bytes) { if (File.Exists(path)) File.Delete(path); else { string parent = Path.GetDirectoryName(path); if (!Directory.Exists(parent)) Directory.CreateDirectory(parent); } File.WriteAllBytes(path, bytes); } public static string FileMd5(string file) { return MD5Utility.FileMd5(file); }}
using UnityEngine;using System.Collections;using System.Diagnostics;using System.IO;public class XMobileUtility{ ////// 复制内容到剪切版 /// /// public static void CopyClipboard(string value) { #if UNITY_EDITOR#elif UNITY_ANDROID using (AndroidJavaObject currentActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic("currentActivity")) { string clipboard = new AndroidJavaClass("android.content.Context").GetStatic ("CLIPBOARD_SERVICE"); using (AndroidJavaObject clipboardManager = currentActivity.Call ("getSystemService", clipboard)) { clipboardManager.Call("setText", value); } }#elif UNITY_IOS#endif } /// /// 修改app的屏幕亮度 /// /// 亮度值,Brightness的有效范围是0~1,-1。 若设置为-1则跟随系统亮度 public static void SetApplicationBrightness(float Brightness) { #if UNITY_EDITOR#elif UNITY_ANDROID AndroidJavaObject Activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic("currentActivity"); Activity.Call("runOnUiThread", new AndroidJavaRunnable(() => { AndroidJavaObject Window = null, Attributes = null; Window = Activity.Call ("getWindow"); Attributes = Window.Call ("getAttributes"); Attributes.Set("screenBrightness", Brightness); Window.Call("setAttributes", Attributes); }));#endif } public static float GetApplicationBrightness() { #if UNITY_EDITOR#elif UNITY_ANDROID using (AndroidJavaObject Activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic ("currentActivity")) { AndroidJavaObject ContentResolver = Activity.Call ("getContentResolver"); AndroidJavaClass SystemSetting = new AndroidJavaClass("android.provider.Settings$System"); float SystemBrightness = SystemSetting.CallStatic ("getInt", ContentResolver, "screen_brightness") / 256.0f; return SystemBrightness; }#endif return 1; } public static float GetActivityBrightness() { #if UNITY_EDITOR#elif UNITY_ANDROID using (AndroidJavaObject Activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic ("currentActivity")) { AndroidJavaObject Window = Activity.Call ("getWindow"); AndroidJavaObject Attributes = Window.Call ("getAttributes"); float Brightness = Attributes.Get ("screenBrightness"); return Brightness; }#endif return 1; } /// /// 重启游戏 /// public static void RestartApplication() { #if UNITY_EDITOR#elif UNITY_STANDALONE_WIN Application.Quit(); string exepath = Path.Combine(Application.dataPath, string.Format("../{0}.exe", Application.productName)); Process.Start(exepath);#elif UNITY_ANDROID AndroidJavaObject activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic("currentActivity"); string packageName = activity.Call ("getPackageName"); AndroidJavaRunnable androidJavaRunnable = new AndroidJavaRunnable(() => { AndroidJavaObject launchIntent = activity.Call ("getPackageManager").Call ("getLaunchIntentForPackage", packageName); ; launchIntent.Call ("addFlags",new AndroidJavaClass("android.content.Intent").GetStatic ("FLAG_ACTIVITY_CLEAR_TOP")); activity.Call("startActivity", launchIntent); using (AndroidJavaClass process = new AndroidJavaClass("android.os.Process")) { process.CallStatic("killProcess", process.CallStatic ("myPid")); process.Dispose(); } }); AndroidJavaObject androidJavaThread = new AndroidJavaObject("java.lang.Thread", androidJavaRunnable); androidJavaThread.Call("start"); activity.Call("finish");#elif UNITY_IOS#endif } /// /// 重启游戏 /// 完全重启 /// public static void RestartApplicationFull() { #if UNITY_EDITOR#elif UNITY_ANDROID using (AndroidJavaObject activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic("currentActivity")) { string packageName = activity.Call ("getPackageName"); AndroidJavaObject restartIntent = activity.Call ("getPackageManager").Call ("getLaunchIntentForPackage", packageName); using (AndroidJavaClass PendingIntent = new AndroidJavaClass("android.app.PendingIntent")) { AndroidJavaObject intent = PendingIntent.CallStatic ("getActivity", activity, 0, restartIntent, 0); string context_ALARM_SERVICE = new AndroidJavaClass("android.content.Context").GetStatic ("ALARM_SERVICE"); int rtc = new AndroidJavaClass("android.app.AlarmManager").GetStatic ("RTC"); long currentTimeMillis = new AndroidJavaClass("java.lang.System").CallStatic ("currentTimeMillis"); AndroidJavaObject manager = activity.Call ("getSystemService", context_ALARM_SERVICE); manager.Call("set", rtc, currentTimeMillis, intent); PendingIntent.Dispose(); } activity.Call("finish"); using (AndroidJavaClass process = new AndroidJavaClass("android.os.Process")) { process.CallStatic("killProcess", process.CallStatic ("myPid")); process.Dispose(); } restartIntent.Dispose(); activity.Dispose(); }#elif UNITY_IOS#endif } /// /// 检查权限是否获取 /// /// ///// public static bool CheckPermission(string name) { bool result = false; if (string.IsNullOrEmpty(name)) return result;#if UNITY_EDITOR#elif UNITY_ANDROID //AndroidJNIHelper.debug = true; using (AndroidJavaObject activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic ("currentActivity")) { //int permission_granted = new AndroidJavaClass("android.content.pm.PackageManager").GetStatic ("PERMISSION_GRANTED"); //int checkCallingOrSelfPermissionResult = activity.Call ("checkCallingOrSelfPermission", name); //result = permission_granted == checkCallingOrSelfPermissionResult; //Debug.LogFormat("checkCallingOrSelfPermissionResult:{0}", checkCallingOrSelfPermissionResult); string packageName = activity.Call ("getPackageName"); AndroidJavaObject packageManager = activity.Call ("getPackageManager"); int permission_granted = new AndroidJavaClass("android.content.pm.PackageManager").GetStatic ("PERMISSION_GRANTED"); UnityEngine.Debug.LogFormat("permission_granted:{0} name:{1} checkPermission:{2} getPackageName:{3}", permission_granted, name, packageManager.Call ("checkPermission", name, packageName), packageName); result = permission_granted == packageManager.Call ("checkPermission", name, packageName); }#elif UNITY_IOS#endif return result; } /// /// 获取清单文件的 targetSdkVersion /// ///public static int GetTargetSdkVersion() { int result = -1;#if UNITY_EDITOR#elif UNITY_ANDROID using (AndroidJavaObject activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic ("currentActivity")) { result = activity.Call ("getApplicationInfo").Get ("targetSdkVersion"); }#elif UNITY_IOS#endif return result; } /// /// 获取编译sdk版本 /// ///public static int GetBuildSdkVersion() { int result = -1;#if UNITY_EDITOR#elif UNITY_ANDROID using (AndroidJavaClass Build_Version = new AndroidJavaClass("android.os.Build.VERSION")) { result = Build_Version.GetStatic ("SDK_INT"); }#elif UNITY_IOS#endif return result; }}
using UnityEngine;using System.Collections;public static class XStringUtility{ public static bool EndsWithEx(this string a, string b) { int ap = a.Length - 1; int bp = b.Length - 1; while (ap >= 0 && bp >= 0 && a[ap] == b[bp]) { ap--; bp--; } return (bp < 0 && a.Length >= b.Length) || (ap < 0 && b.Length >= a.Length); } public static bool StartsWithEx(this string a, string b) { int aLen = a.Length; int bLen = b.Length; int ap = 0; int bp = 0; while (ap < aLen && bp < bLen && a[ap] == b[bp]) { ap++; bp++; } return (bp == bLen && aLen >= bLen) || (ap == aLen && bLen >= aLen); }}
using UnityEngine;using System.Collections;using System.Text;public class XUtility{ public static System.Reflection.Assembly LoadAssembly(string file) { return System.Reflection.Assembly.Load(System.IO.File.ReadAllBytes(file)); } public static string FormatBytes(long bytes) { string result = string.Empty; if (bytes >= 1048576) result = string.Format("{0} MB", (bytes / 1048576f).ToString("f2")); else if (bytes >= 1024) result = string.Format("{0} KB", (bytes / 1024f).ToString("f2")); else result = string.Format("{0} B", bytes); return result; } public static string FormatBytes(double bytes) { return FormatBytes((long)bytes); } //加层 public static int AddMask(int target, params int[] masks) { for (int i = 0; i < masks.Length; i++) target |= 1 << masks[i]; return target; } //减层 public static int SubMask(int target, params int[] masks) { for (int i = 0; i < masks.Length; i++) target &= ~(1 << masks[i]); return target; } public static bool ScreenPointToScene(Vector3 screenPos, out RaycastHit hitInfo, params string[] layerMask) { screenPos = XCamera.mainCamera.ViewportToScreenPoint(XCamera.guiCamera.ScreenToViewportPoint(screenPos)); Ray ray = XCamera.mainCamera.ScreenPointToRay(screenPos); bool b = Physics.Raycast(ray, out hitInfo, Mathf.Infinity, LayerMask.GetMask(layerMask)); Debug.DrawRay(ray.origin, ray.direction * 1000f, b ? Color.green : Color.red, 3f); return b; } //当前游戏版本 public static string GetGameVerion() { StringBuilder sb = new StringBuilder(); if (XAssetsFiles.s_CurrentVersion != null) { sb.AppendFormat("Art {0}", Application.version); sb.AppendFormat(".{0}", XAssetsFiles.s_CurrentVersion.p_ArtVersion.svnVer); sb.Append("\n"); sb.AppendFormat("Dev {0}", Application.version); sb.AppendFormat(".{0}", XAssetsFiles.s_CurrentVersion.p_DevVersion.svnVer); } else { sb.Append(Application.version); } return sb.ToString(); } //是否有连上wifi/4g/或有线 public static bool IsNetworkValid() { return Application.internetReachability != NetworkReachability.NotReachable; } //是否为wifi下 public static bool IsNetworkWifi() { return Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork; } //是否为移动网络 public static bool IsNetwork4G() { return Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork; }}
转载地址:http://wbrxo.baihongyu.com/