using UnityEngine;
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using ICSharpCode.SharpZipLib.GZip;
using System.Reflection;
public static class Util
{
public static string TheWebConfigURL;
public static int Int(object o) {
return Convert.ToInt32(o);
}
public static float Float(object o) {
return (float)Math.Round(Convert.ToSingle(o), 2);
}
public static long Long(object o) {
return Convert.ToInt64(o);
}
public static int Random(int min, int max) {
return UnityEngine.Random.Range(min, max);
}
public static float Random(float min, float max) {
return UnityEngine.Random.Range(min, max);
}
public static string Uid(string uid) {
int position = uid.LastIndexOf('_');
return uid.Remove(0, position + 1);
}
public static long GetTime() {
TimeSpan ts = new TimeSpan(DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks);
return (long)ts.TotalMilliseconds;
}
/// <summary>
/// 搜索子物體組件-GameObject版
/// </summary>
public static T Get<T>(GameObject go, string subnode) where T : Component {
if (go != null) {
Transform sub = go.transform.FindChild(subnode);
if (sub != null) return sub.GetComponent<T>();
}
return null;
}
/// <summary>
/// 搜索子物體組件-Transform版
/// </summary>
public static T Get<T>(Transform go, string subnode) where T : Component {
if (go != null) {
Transform sub = go.FindChild(subnode);
if (sub != null) return sub.GetComponent<T>();
}
return null;
}
/// <summary>
/// 搜索子物體組件-Component版
/// </summary>
public static T Get<T>(Component go, string subnode) where T : Component {
return go.transform.FindChild(subnode).GetComponent<T>();
}
/// <summary>
/// 添加組件
/// </summary>
public static T Add<T>(GameObject go) where T : Component {
if (go != null) {
T[] ts = go.GetComponents<T>();
for (int i = 0; i < ts.Length; i++ ) {
if (ts[i] != null) GameObject.Destroy(ts[i]);
}
return go.gameObject.AddComponent<T>();
}
return null;
}
/// <summary>
/// 添加組件
/// </summary>
public static T Add<T>(Transform go) where T : Component {
return Add<T>(go.gameObject);
}
/// <summary>
/// 查找子對(duì)象
/// </summary>
public static GameObject Child(GameObject go, string subnode) {
return Child(go.transform, subnode);
}
/// <summary>
/// 查找子對(duì)象
/// </summary>
public static GameObject Child(Transform go, string subnode) {
Transform tran = go.FindChild(subnode);
if (tran == null) return null;
return tran.gameObject;
}
/// <summary>
/// 取平級(jí)對(duì)象
/// </summary>
public static GameObject Peer(GameObject go, string subnode) {
return Peer(go.transform, subnode);
}
/// <summary>
/// 取平級(jí)對(duì)象
/// </summary>
public static GameObject Peer(Transform go, string subnode) {
Transform tran = go.parent.FindChild(subnode);
if (tran == null) return null;
return tran.gameObject;
}
/// <summary>
/// 手機(jī)震動(dòng)
/// </summary>
public static void Vibrate() {
//int canVibrate = PlayerPrefs.GetInt(Const.AppPrefix + "Vibrate", 1);
//if (canVibrate == 1) iPhoneUtils.Vibrate();
}
/// <summary>
/// Base64編碼
/// </summary>
public static string EncodeBase64(string message) {
byte[] bytes = Encoding.GetEncoding("utf-8").GetBytes(message);
return Convert.ToBase64String(bytes);
}
/// <summary>
/// Base64解碼
/// </summary>
public static string DecodeBase64(string message) {
byte[] bytes = Convert.FromBase64String(message);
return Encoding.GetEncoding("utf-8").GetString(bytes);
}
/// <summary>
/// 判斷數(shù)字
/// </summary>
public static bool IsNumeric(string str) {
if (str == null || str.Length == 0) return false;
for (int i = 0; i < str.Length; i++ ) {
if (!Char.IsNumber(str[i])) { return false; }
}
return true;
}
public static string IntToStringWithW(int num)
{
if (num >= 10000)
return (num / 10000).ToString() + "萬(wàn)";
if(num >= 100000000)
return (num / 100000000).ToString() + "億";
return num.ToString();
}
/// <summary>
/// HashToMD5Hex
/// </summary>
public static string HashToMD5Hex(string sourceStr) {
byte[] Bytes = Encoding.UTF8.GetBytes(sourceStr);
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider()) {
byte[] result = md5.ComputeHash(Bytes);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < result.Length; i++)
builder.Append(result[i].ToString("x2"));
return builder.ToString();
}
}
/// <summary>
/// 計(jì)算字符串的MD5值
/// </summary>
public static string md5(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;
}
/// <summary>
/// 計(jì)算文件的MD5值
/// </summary>
public static string md5file(string file) {
try {
FileStream fs = new FileStream(file, FileMode.Open,FileAccess.Read, FileShare.Read);
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);
}
}
/// <summary>
/// 功能:壓縮字符串
/// </summary>
/// <param name="infile">被壓縮的文件路徑</param>
/// <param name="outfile">生成壓縮文件的路徑</param>
public static void CompressFile(string infile, string outfile) {
Stream gs = new GZipOutputStream(File.Create(outfile));
FileStream fs = File.OpenRead(infile);
byte[] writeData = new byte[fs.Length];
fs.Read(writeData, 0, (int)fs.Length);
gs.Write(writeData, 0, writeData.Length);
gs.Close(); fs.Close();
}
/// <summary>
/// 功能:輸入文件路徑音羞,返回解壓后的字符串
/// </summary>
public static string DecompressFile(string infile) {
string result = string.Empty;
Stream gs = new GZipInputStream(File.OpenRead(infile));
MemoryStream ms = new MemoryStream();
int size = 2048;
byte[] writeData = new byte[size];
while (true) {
size = gs.Read(writeData, 0, size);
if (size > 0) {
ms.Write(writeData, 0, size);
} else {
break;
}
}
result = new UTF8Encoding().GetString(ms.ToArray());
gs.Close(); ms.Close();
return result;
}
/// <summary>
/// 壓縮字符串
/// </summary>
public static string Compress(string source) {
byte[] data = Encoding.UTF8.GetBytes(source);
MemoryStream ms = null;
using (ms = new MemoryStream()) {
using (Stream stream = new GZipOutputStream(ms)) {
try {
stream.Write(data, 0, data.Length);
} finally {
stream.Close();
ms.Close();
}
}
}
return Convert.ToBase64String(ms.ToArray());
}
/// <summary>
/// 解壓字符串
/// </summary>
public static string Decompress(string source) {
string result = string.Empty;
byte[] buffer = null;
try {
buffer = Convert.FromBase64String(source);
} catch {
Debug.LogError("Decompress---->>>>" + source);
}
using (MemoryStream ms = new MemoryStream(buffer)) {
using (Stream sm = new GZipInputStream(ms)) {
StreamReader reader = new StreamReader(sm, Encoding.UTF8);
try {
result = reader.ReadToEnd();
} finally {
sm.Close();
ms.Close();
}
}
}
return result;
}
/// <summary>
/// 清除所有子節(jié)點(diǎn)
/// </summary>
public static void ClearChild(Transform go) {
if (go == null) return;
for (int i = go.childCount - 1; i >= 0; i--) {
GameObject.Destroy(go.GetChild(i).gameObject);
}
}
/// <summary>
/// 生成一個(gè)Key名
/// </summary>
public static string GetKey(string key) {
return Const.AppPrefix + Const.UserId + "_" + key;
}
/// <summary>
/// 取得整型
/// </summary>
public static int GetInt(string key) {
string name = GetKey(key);
return PlayerPrefs.GetInt(name);
}
/// <summary>
/// 有沒(méi)有值
/// </summary>
public static bool HasKey(string key) {
string name = GetKey(key);
return PlayerPrefs.HasKey(name);
}
/// <summary>
/// 保存整型
/// </summary>
public static void SetInt(string key, int value) {
string name = GetKey(key);
PlayerPrefs.DeleteKey(name);
PlayerPrefs.SetInt(name, value);
}
/// <summary>
/// 取得數(shù)據(jù)
/// </summary>
public static string GetString(string key) {
string name = GetKey(key);
return PlayerPrefs.GetString(name);
}
/// <summary>
/// 保存數(shù)據(jù)
/// </summary>
public static void SetString(string key, string value) {
string name = GetKey(key);
PlayerPrefs.DeleteKey(name);
PlayerPrefs.SetString(name, value);
}
/// <summary>
/// 刪除數(shù)據(jù)
/// </summary>
public static void RemoveData(string key) {
string name = GetKey(key);
PlayerPrefs.DeleteKey(name);
}
/// <summary>
/// 清理內(nèi)存
/// </summary>
public static void ClearMemory() {
//GC.Collect();
Resources.UnloadUnusedAssets();
}
/// <summary>
/// 是否為數(shù)字
/// </summary>
public static bool IsNumber(string strNumber) {
Regex regex = new Regex("[^0-9]");
return !regex.IsMatch(strNumber);
}
/// <summary>
/// 取得數(shù)據(jù)存放目錄
/// </summary>
public static string DataPath {
get {
//string game = Const.AppName.ToLower();
//if (Application.platform == RuntimePlatform.IPhonePlayer ||
// Application.platform == RuntimePlatform.Android ||
// Application.platform == RuntimePlatform.WP8Player) {
// return Application.persistentDataPath + "/" + game + "/";
//}
//if (Application.platform == RuntimePlatform.WindowsWebPlayer) {
// return "web/";
//}
//#if UNITY_WEBPLAYER
//if(!String.IsNullOrEmpty(TheWebConfigURL))
//{
// return TheWebConfigURL + "/StreamingAssets/WebPlayer/";
//}
//return "file://" + Application.dataPath + "/StreamingAssets/WebPlayer/";
//#endif
//if (Const.DebugMode) {
// string target = string.Empty;
// if (Application.platform == RuntimePlatform.OSXEditor ||
// Application.platform == RuntimePlatform.IPhonePlayer ||
// Application.platform == RuntimePlatform.OSXEditor) {
// target = "ios";
// }
// else if (Application.platform == RuntimePlatform.Android)
// {
// target = "android";
// }
// else {
// }
// return Application.dataPath + "/StreamingAssets/" + target + "/";
//}
//return Application.dataPath + "/persistentDataPath/";
return Util.AppContentPath();
}
}
#if !UNITY_WEBPLAYER
/// <summary>
/// 取得行文本
/// </summary>
public static string GetFileText(string path) {
return File.ReadAllText(path);
//return "";
}
#endif
/// <summary>
/// 網(wǎng)絡(luò)可用
/// </summary>
public static bool NetAvailable {
get {
return Application.internetReachability != NetworkReachability.NotReachable;
}
}
/// <summary>
/// 是否是無(wú)線
/// </summary>
public static bool IsWifi {
get {
return Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork;
}
}
/// <summary>
/// 應(yīng)用程序內(nèi)容路徑
/// </summary>
public static string AppContentPath() {
return GetAppContentPath(Application.platform);
}
public static string GetAppContentPath(RuntimePlatform platform) {
string path = string.Empty;
#if UNITY_WEBPLAYER && UNITY_EDITOR
path = "file://" + Application.dataPath + "/streamingassets/webplayer/";
#endif
#if UNITY_WEBPLAYER && !UNITY_EDITOR
path = Application.dataPath + "/streamingassets/webplayer/";
#endif
#if (UNITY_STANDALONE || UNITY_STANDALONE_WIN) && !UNITY_EDITOR
//path = "file://" + Application.dataPath + "/streamingassets/windows32/";
path = PathSetting.resourcePath;//"http://cdn1.app99.wsdo.xnhdgame.com/dance/streamingassets/windows32/windows32/";
#endif
#if (UNITY_STANDALONE || UNITY_STANDALONE_WIN) && UNITY_EDITOR
path = "file://" + Application.dataPath + "/streamingassets/windows32/";
#endif
/*
#if UNITY_WEBPLAYER
#if UNITY_EDITOR
if(!String.IsNullOrEmpty(TheWebConfigURL))
{
return TheWebConfigURL + "/streamingassets/webplayer/";
}
else
{
path = "file://" + Application.dataPath + "/streamingassets/webplayer/";
}
#else
path = Application.dataPath + "/streamingassets/webplayer/";
#endif
#else
switch (Application.platform) {
case RuntimePlatform.Android:
path = "jar:file://" + Application.dataPath + "!/assets/Android/";
break;
case RuntimePlatform.IPhonePlayer:
path = Application.dataPath + "/Raw/IOS/";
break;
case RuntimePlatform.OSXPlayer:
case RuntimePlatform.OSXEditor:
path = Application.dataPath + "/StreamingAssets/Mac/";
break;
case RuntimePlatform.WindowsEditor:
case RuntimePlatform.WindowsPlayer:
path = "file://" + Application.dataPath + "/StreamingAssets/Windows32/";
break;
case RuntimePlatform.WindowsWebPlayer:
path = Application.dataPath + "/streamingassets/webplayer/";
break;
default:
path = Application.dataPath + "/StreamingAssets/Android/";
break;
}
#endif
*/
return path;
}
/// <summary>
/// 添加lua單機(jī)事件
/// </summary>
public static void AddClick(GameObject go, System.Object luafuc) {
UIEventListener.Get(go).onClick += delegate(GameObject o) {
// LuaInterface.LuaFunction func = (LuaInterface.LuaFunction)luafuc;
// func.Call();
};
}
public static string LuaPath() {
if (Const.DebugMode) {
return Application.dataPath + "/lua/";
}
return DataPath + "st/";
}
/// <summary>
/// 取得Lua路徑
/// </summary>
public static string LuaPath(string name) {
string lowerName = name.ToLower();
string path = LuaPath();
if (lowerName.EndsWith(".ab")) {
return path+ name;
}
return path + name + ".ab";
}
public static GameObject LoadAsset(AssetBundle bundle, string name) {
#if UNITY_5
return bundle.LoadAsset(name, typeof(GameObject)) as GameObject;
#else
return bundle.Load(name, typeof(GameObject)) as GameObject;
#endif
}
public static Component AddComponent(GameObject go, string assembly, string classname) {
Assembly asmb = Assembly.Load(assembly);
Type t = asmb.GetType(assembly + "." + classname);
Component com = go.GetComponent(t);
if (com == null)
{
return go.AddComponent(t);
}
return com;
}
public static bool TryAddValue<T, K>(this Dictionary<T, K> dic, T key, K value) {
if (dic.ContainsKey(key)) {
dic[key] = value;
return false;
}
else {
dic.Add(key, value);
return true;
}
}
public static int GetStringByteCount2(string str)
{
if (str.Equals(string.Empty))
return 0;
int strlen = 0;
byte[] strBytes = System.Text.Encoding.Unicode.GetBytes(str);
for (int i = 0; i <= strBytes.Length - 1; i++)
{
if (strBytes[i] != 0)
strlen++;
}
return strlen;
}
public static int GetStringByteCount(string str)
{
if (str.Equals(string.Empty))
return 0;
int strlen = 0;
foreach (char c in str.ToCharArray())
{
if (Regex.IsMatch(c.ToString(), @"[\u4e00-\u9fa5]"))
{
strlen += 2;
}
else
{
strlen++;
}
}
return strlen;
}
public static bool isWebPlayer
{
get
{
return Application.platform == RuntimePlatform.WindowsWebPlayer ||
Application.platform == RuntimePlatform.OSXWebPlayer;
}
}
public static bool isEditor
{
get
{
#if UNITY_EDITOR
return true;
#endif
return false;
}
}
}
util代碼
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
- 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)试幽,“玉大人筝蚕,你說(shuō)我怎么就攤上這事∑涛耄” “怎么了起宽?”我有些...
- 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)康震。 經(jīng)常有香客問(wèn)我燎含,道長(zhǎng),這世上最難降的妖魔是什么腿短? 我笑而不...
- 正文 為了忘掉前任,我火速辦了婚禮绘梦,結(jié)果婚禮上橘忱,老公的妹妹穿的比我還像新娘。我一直安慰自己卸奉,他們只是感情好钝诚,可當(dāng)我...
- 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著榄棵,像睡著了一般凝颇。 火紅的嫁衣襯著肌膚如雪潘拱。 梳的紋絲不亂的頭發(fā)上,一...
- 那天拧略,我揣著相機(jī)與錄音芦岂,去河邊找鬼。 笑死垫蛆,一個(gè)胖子當(dāng)著我的面吹牛禽最,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播袱饭,決...
- 文/蒼蘭香墨 我猛地睜開(kāi)眼川无,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了虑乖?” 一聲冷哼從身側(cè)響起懦趋,我...
- 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎疹味,沒(méi)想到半個(gè)月后愕够,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
- 正文 獨(dú)居荒郊野嶺守林人離奇死亡佛猛,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
- 正文 我和宋清朗相戀三年惑芭,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片继找。...
- 正文 年R本政府宣布边臼,位于F島的核電站哄尔,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏柠并。R本人自食惡果不足惜岭接,卻給世界環(huán)境...
- 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望臼予。 院中可真熱鬧鸣戴,春花似錦、人聲如沸粘拾。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)缰雇。三九已至入偷,卻和暖如春追驴,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背疏之。 一陣腳步聲響...
- 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像拓哟,于是被迫代替她去往敵國(guó)和親几缭。 傳聞我的和親對(duì)象是個(gè)殘疾皇子河泳,可洞房花燭夜當(dāng)晚...
推薦閱讀更多精彩內(nèi)容
- 如何在Swift的代碼中使用OC的代碼, 在OC的代碼中使用Swift的代碼? 一、OC的代碼中使用Swift代碼...
- Xamarin XAML語(yǔ)言教程構(gòu)建ControlTemplate控件模板 控件模板ControlTemplate...
- 復(fù)雜的故事簡(jiǎn)單說(shuō),復(fù)雜的問(wèn)題簡(jiǎn)單做备禀,您好洲拇,這里是簡(jiǎn)露一手,歡迎瀏覽曲尸。 簡(jiǎn)述 經(jīng)常:提交代碼到SVN比對(duì)赋续,發(fā)現(xiàn)代碼被...
- 一.git版本控制原理#### master(主分支), develop(分支),雖然是主分支和分支,卻是平級(jí)關(guān)系...
- 文︱芳小哇 圖︱網(wǎng)絡(luò) 曾經(jīng)和朋友談?wù)撨^(guò)一個(gè)問(wèn)題,自我增值的最好時(shí)期昆箕,究竟是什么時(shí)候鸦列? 我們一致得出的共同結(jié)果都是...