Utility
程序员文章站
2022-05-09 13:32:37
...
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(); }
/// <summary>
/// 获取时间戳
/// </summary>
/// <returns></returns>
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);
}
/// <summary>
/// 保存存在一定时间的本地数据
/// </summary>
/// <param name="key"></param>
/// <param name="seconds"></param>
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<SaveData>(json);
return saveData;
}
catch (Exception e)
{
Debug.LogError("LocalCacheUtility::GetTimeData() " + e.ToString());
}
return null;
}
/// <summary>
/// 将缓存保存天数
/// </summary>
/// <param name="key"></param>
/// <param name="day"></param>
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
{
/// <summary>
/// 复制内容到剪切版
/// </summary>
/// <param name="value"></param>
public static void CopyClipboard(string value)
{
#if UNITY_EDITOR
#elif UNITY_ANDROID
using (AndroidJavaObject currentActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity"))
{
string clipboard = new AndroidJavaClass("android.content.Context").GetStatic<string>("CLIPBOARD_SERVICE");
using (AndroidJavaObject clipboardManager = currentActivity.Call<AndroidJavaObject>("getSystemService", clipboard))
{
clipboardManager.Call("setText", value);
}
}
#elif UNITY_IOS
#endif
}
/// <summary>
/// 修改app的屏幕亮度
/// </summary>
/// <param name="Brightness">亮度值,Brightness的有效范围是0~1,-1。 若设置为-1则跟随系统亮度</param>
public static void SetApplicationBrightness(float Brightness)
{
#if UNITY_EDITOR
#elif UNITY_ANDROID
AndroidJavaObject Activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");
Activity.Call("runOnUiThread", new AndroidJavaRunnable(() => {
AndroidJavaObject Window = null, Attributes = null;
Window = Activity.Call<AndroidJavaObject>("getWindow");
Attributes = Window.Call<AndroidJavaObject>("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<AndroidJavaObject>("currentActivity"))
{
AndroidJavaObject ContentResolver = Activity.Call<AndroidJavaObject>("getContentResolver");
AndroidJavaClass SystemSetting = new AndroidJavaClass("android.provider.Settings$System");
float SystemBrightness = SystemSetting.CallStatic<int>("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<AndroidJavaObject>("currentActivity"))
{
AndroidJavaObject Window = Activity.Call<AndroidJavaObject>("getWindow");
AndroidJavaObject Attributes = Window.Call<AndroidJavaObject>("getAttributes");
float Brightness = Attributes.Get<float>("screenBrightness");
return Brightness;
}
#endif
return 1;
}
/// <summary>
/// 重启游戏
/// </summary>
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<AndroidJavaObject>("currentActivity");
string packageName = activity.Call<string>("getPackageName");
AndroidJavaRunnable androidJavaRunnable = new AndroidJavaRunnable(() =>
{
AndroidJavaObject launchIntent =
activity.Call<AndroidJavaObject>("getPackageManager").Call<AndroidJavaObject>("getLaunchIntentForPackage", packageName); ;
launchIntent.Call<AndroidJavaObject>("addFlags",new AndroidJavaClass("android.content.Intent").GetStatic<int>("FLAG_ACTIVITY_CLEAR_TOP"));
activity.Call("startActivity", launchIntent);
using (AndroidJavaClass process = new AndroidJavaClass("android.os.Process"))
{
process.CallStatic("killProcess", process.CallStatic<int>("myPid"));
process.Dispose();
}
});
AndroidJavaObject androidJavaThread = new AndroidJavaObject("java.lang.Thread", androidJavaRunnable);
androidJavaThread.Call("start");
activity.Call("finish");
#elif UNITY_IOS
#endif
}
/// <summary>
/// 重启游戏
/// 完全重启
/// </summary>
public static void RestartApplicationFull()
{
#if UNITY_EDITOR
#elif UNITY_ANDROID
using (AndroidJavaObject activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity"))
{
string packageName = activity.Call<string>("getPackageName");
AndroidJavaObject restartIntent = activity.Call<AndroidJavaObject>("getPackageManager").Call<AndroidJavaObject>("getLaunchIntentForPackage", packageName);
using (AndroidJavaClass PendingIntent = new AndroidJavaClass("android.app.PendingIntent"))
{
AndroidJavaObject intent = PendingIntent.CallStatic<AndroidJavaObject>("getActivity", activity, 0, restartIntent, 0);
string context_ALARM_SERVICE = new AndroidJavaClass("android.content.Context").GetStatic<string>("ALARM_SERVICE");
int rtc = new AndroidJavaClass("android.app.AlarmManager").GetStatic<int>("RTC");
long currentTimeMillis = new AndroidJavaClass("java.lang.System").CallStatic<long>("currentTimeMillis");
AndroidJavaObject manager = activity.Call<AndroidJavaObject>("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<int>("myPid"));
process.Dispose();
}
restartIntent.Dispose();
activity.Dispose();
}
#elif UNITY_IOS
#endif
}
/// <summary>
/// 检查权限是否获取
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
//<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>
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<AndroidJavaObject>("currentActivity"))
{
//int permission_granted = new AndroidJavaClass("android.content.pm.PackageManager").GetStatic<int>("PERMISSION_GRANTED");
//int checkCallingOrSelfPermissionResult = activity.Call<int>("checkCallingOrSelfPermission", name);
//result = permission_granted == checkCallingOrSelfPermissionResult;
//Debug.LogFormat("checkCallingOrSelfPermissionResult:{0}", checkCallingOrSelfPermissionResult);
string packageName = activity.Call<string>("getPackageName");
AndroidJavaObject packageManager = activity.Call<AndroidJavaObject>("getPackageManager");
int permission_granted = new AndroidJavaClass("android.content.pm.PackageManager").GetStatic<int>("PERMISSION_GRANTED");
UnityEngine.Debug.LogFormat("permission_granted:{0} name:{1} checkPermission:{2} getPackageName:{3}", permission_granted, name, packageManager.Call<int>("checkPermission", name, packageName), packageName);
result = permission_granted == packageManager.Call<int>("checkPermission", name, packageName);
}
#elif UNITY_IOS
#endif
return result;
}
/// <summary>
/// 获取清单文件的 targetSdkVersion
/// </summary>
/// <returns></returns>
public static int GetTargetSdkVersion()
{
int result = -1;
#if UNITY_EDITOR
#elif UNITY_ANDROID
using (AndroidJavaObject activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity"))
{
result = activity.Call<AndroidJavaObject>("getApplicationInfo").Get<int>("targetSdkVersion");
}
#elif UNITY_IOS
#endif
return result;
}
/// <summary>
/// 获取编译sdk版本
/// </summary>
/// <returns></returns>
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<int>("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; }
}
上一篇: Django web框架-----视图与网址的不同请求方式
下一篇: Web框架Django
推荐阅读
-
mstar isp utility怎么使用?mstar isp utility详细使用图文教程
-
使用DBNEWID Utility 修改oracle数据库的 db name 和 dbid
-
RxSwift笔记 - Observable Utility Operators
-
电脑总弹出NI Circuit Design Suite Support and Upgrade Utility的原因及解决方法
-
Serial Port Utility怎么用?Serial Port Utility安装使用图文教程
-
使用SQLdiag Utility搜集SQL Server诊断信息
-
STM32开发,通过SWO功能输出Printf函数到Utility
-
使用DBNEWID Utility 修改oracle数据库的 db name 和 dbid
-
介绍DB2新概念:Ingest Utility支持的各种文件格式
-
jQuery Ajax 仿AjaxPro.Utility.RegisterTypeForAjax辅助方法_jquery