util代碼

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;
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市苇倡,隨后出現(xiàn)的幾起案子彪见,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,590評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件彤守,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡哭靖,警方通過(guò)查閱死者的電腦和手機(jī)具垫,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)试幽,“玉大人筝蚕,你說(shuō)我怎么就攤上這事∑涛耄” “怎么了起宽?”我有些...
    開(kāi)封第一講書(shū)人閱讀 169,301評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)康震。 經(jīng)常有香客問(wèn)我燎含,道長(zhǎng),這世上最難降的妖魔是什么腿短? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 60,078評(píng)論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮绘梦,結(jié)果婚禮上橘忱,老公的妹妹穿的比我還像新娘。我一直安慰自己卸奉,他們只是感情好钝诚,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,082評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著榄棵,像睡著了一般凝颇。 火紅的嫁衣襯著肌膚如雪潘拱。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 52,682評(píng)論 1 312
  • 那天拧略,我揣著相機(jī)與錄音芦岂,去河邊找鬼。 笑死垫蛆,一個(gè)胖子當(dāng)著我的面吹牛禽最,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播袱饭,決...
    沈念sama閱讀 41,155評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼川无,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了虑乖?” 一聲冷哼從身側(cè)響起懦趋,我...
    開(kāi)封第一講書(shū)人閱讀 40,098評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎疹味,沒(méi)想到半個(gè)月后愕够,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,638評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡佛猛,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,701評(píng)論 3 342
  • 正文 我和宋清朗相戀三年惑芭,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片继找。...
    茶點(diǎn)故事閱讀 40,852評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡遂跟,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出婴渡,到底是詐尸還是另有隱情幻锁,我是刑警寧澤,帶...
    沈念sama閱讀 36,520評(píng)論 5 351
  • 正文 年R本政府宣布边臼,位于F島的核電站哄尔,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏柠并。R本人自食惡果不足惜岭接,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,181評(píng)論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望臼予。 院中可真熱鬧鸣戴,春花似錦、人聲如沸粘拾。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,674評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)缰雇。三九已至入偷,卻和暖如春追驴,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背疏之。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,788評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工殿雪, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留宿饱,地道東北人爹橱。 一個(gè)月前我還...
    沈念sama閱讀 49,279評(píng)論 3 379
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像拓哟,于是被迫代替她去往敵國(guó)和親几缭。 傳聞我的和親對(duì)象是個(gè)殘疾皇子河泳,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,851評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容