下面是一些简单的工具函数,常用而已。。。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.SceneManagement;
using System.IO;

public class TestTool : MonoBehaviour {
    
    // 获取相对路径
    public static string GetObjectPath (this GameObject theObject)
    {
        List<string> aStringList = new List<string>();
        Transform aTransform = theObject.transform;
        do
        {
            aStringList.Add(aTransform.name);
            aTransform = aTransform.parent;
        }
        while (aTransform != null);
        aStringList.Reverse();
        return string.Join("/", aStringList.ToArray());
    }

    // 通过相对路径查找
    public static Transform FindByObjectPath (this Transform parentTransform, string path)
    {
        if (string.IsNullOrEmpty(path) || path.Length < parentTransform.name.Length)
            return null;
        if (path == parentTransform.name)
            return parentTransform;
        return parentTransform.Find(path.Substring(parentTransform.name.Length + 1));
    }

    public static void ShowToast(string text)
    {
        if (Application.platform == RuntimePlatform.Android)
        {
            AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");

            activity.Call("runOnUiThread", new AndroidJavaRunnable(
                ()=>
                {
                    AndroidJavaClass Toast = new AndroidJavaClass("android.widget.Toast");
                    AndroidJavaObject javaString = new AndroidJavaObject("java.lang.String", text);
                    AndroidJavaObject context = activity.Call<AndroidJavaObject>("getApplicationContext");
                    AndroidJavaObject toast = Toast.CallStatic<AndroidJavaObject>("makeText", context,
                        javaString, Toast.GetStatic<int>("LENGTH_SHORT"));
                    toast.Call("show"); }
            ));
        }
    }

    public static void RemoveCloneName (GameObject obj)
    {
        if (obj != null) {
            obj.name = obj.name.Replace ("(Clone)", "");
        }
    }

    static DateTime oldDateTime;
    /// <summary>
    /// 计算经过的时间
    /// </summary>
    public static void GetElapsedTime (bool flag)
    {
        if (flag) {
            oldDateTime = System.DateTime.Now;
        } else {
            DateTime currentTime = System.DateTime.Now;
            TimeSpan timeSpan = currentTime.Subtract(oldDateTime);
            Debug.LogWarning(timeSpan.TotalMilliseconds + " 毫秒");
        }
    }

    /// <summary>
    /// 调整自身和自物体的layer
    /// </summary>
    public static void SetLayerWithChildren (GameObject go, string layerName)
    {
        int layerNumber = LayerMask.NameToLayer (layerName);
        foreach (Transform trans in go.GetComponentsInChildren<Transform>(true)) {
            trans.gameObject.layer = layerNumber;
        }
    }

    /// <summary>
    /// Recursively set the game object's layer.
    /// </summary>
    public static void SetLayer(GameObject go, int layer)
    {
        go.layer = layer;

        var t = go.transform;

        for (int i = 0, imax = t.childCount; i < imax; ++i)
        {
            var child = t.GetChild(i);
            SetLayer(child.gameObject, layer);
        }
    }

    /// <summary>
    /// 缩放粒子大小,该方法不推荐
    /// </summary>
    public static void ScaleParticleSystem (GameObject gameObj, float scaleFactor, bool isScaleGameObj = true)
    {
        var particles = gameObj.GetComponentsInChildren<ParticleSystem> (true);

        if (particles != null && particles.Length > 0) {
            foreach (ParticleSystem p in particles) {
                p.startSize *= scaleFactor;
                p.startSpeed *= scaleFactor;
            }
        }

        if (isScaleGameObj) {
            gameObj.transform.localScale *= scaleFactor;
        }
    }

    /// <summary>
    /// 获得粒子的时长
    /// </summary>
    public static float GetParticleSystemLength (Transform particleTrans)
    {
        ParticleSystem[] particleSystems = particleTrans.GetComponentsInChildren<ParticleSystem> ();
        float maxDuration = 0;
        foreach (ParticleSystem ps in particleSystems) {
            if (ps.emission.enabled) {
                if (ps.loop) {
                    return -1f;
                }
                float dunration = 0f;

                if (ps.emissionRate <= 0) {
                    dunration = ps.startDelay + ps.startLifetime;
                } else {
                    dunration = ps.startDelay + Mathf.Max (ps.duration, ps.startLifetime);
                }
                if (dunration > maxDuration) {
                    maxDuration = dunration;
                }
            }
        }
        return maxDuration;
    }

    /// <summary>
    /// animator中是否有该参数
    /// </summary>
    public static bool HasParameter(string paramName, Animator animator)
    {
        foreach (AnimatorControllerParameter param in animator.parameters)
        {
            if (param.name == paramName) return true;
        }
        return false;
    }

    /// <summary>
    /// 计算抛物线长度,顶点在圆心,公式 y = a * x^2
    /// </summary>
    public static float GetParabolaLength (float distance, float height)
    {
        float x = distance * 0.5f;
        float a = height / (x * x);
        float snap = 0.15f;
        float result = 0;
        float prevYPos = 0;
        for (float i = 0; i < distance * 0.5f;) {
            i += snap;
            float yPos = a * (i * i);
            float heightOffset = yPos - prevYPos;
            prevYPos = yPos;
            result += Mathf.Sqrt (snap * snap + heightOffset * heightOffset);
        }
        return result * 2;
    }

    public static bool IsWifi()
    {
        return Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork;
    }

    /// <summary>
    /// 判断一个数是否2的次方
    /// </summary>
    public static bool CheckPow2(int num)
    {
        int i = 1;
        while (true)
        {
            if (i > num)
                return false;
            if (i == num)
                return true;
            i = i * 2;
        }
    }

    public static string HumanizeTimeString(int seconds)
    {
        TimeSpan ts = TimeSpan.FromSeconds(seconds);
        string timeStr = string.Format("{0}{1}{2}{3}",
            ts.Days == 0 ? "" : ts.Days + "天",
            ts.Hours == 0 ? "" : ts.Hours + "小时",
            ts.Minutes == 0 ? "" : ts.Minutes + "分钟",
            ts.Seconds == 0 ? "" : ts.Seconds + "秒");

        return timeStr;
    }

    public static int GetUtcDay()
    {
        DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
        DateTime now = DateTime.UtcNow;
        var span = now - origin;

        return span.Days;
    }

    public static int GetDeltaMinutes(DateTime origin)
    {
        DateTime now = DateTime.UtcNow;
        var span = now - origin;

        return span.Minutes;
    }

    public static int GetDeltaHours(DateTime origin)
    {
        DateTime now = DateTime.UtcNow;
        var span = now - origin;

        return span.Hours;
    }

    public static int GetDeltaDay(DateTime origin)
    {
        DateTime now = DateTime.UtcNow;
        var span = now - origin;

        return span.Days;
    }

    /// <summary>
    /// Utc毫秒转Utc时间
    /// </summary>
    public static DateTime GetDateTimeByUtcMilliseconds(long utcTime, int zone = 0)
    {
        DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
        return origin.AddMilliseconds(utcTime).AddHours(zone);
    }

    /// <summary>
    /// Utc秒转Utc时间
    /// </summary>
    public static DateTime GetDateTimeByUtcSeconds(double unixTimeStamp, int zone = 0)
    {
        DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
        return origin.AddSeconds(unixTimeStamp).AddHours(zone);
    }

    /// <summary>
    /// Unix时间转毫秒数
    /// </summary>
    /// <returns></returns>
    public static double GetUtcMilliseconds(DateTime date)
    {
        DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
        TimeSpan diff = date - origin;
        return diff.TotalMilliseconds;
    }

    /// <summary>
    /// Unix时间转秒数
    /// </summary>
    /// <returns></returns>
    public static double GetUtcSeconds(DateTime date)
    {
        DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
        TimeSpan diff = date - origin;
        return diff.TotalSeconds;
    }


    /// <summary>
    /// 人性化数字显示,百万,千万,亿
    /// </summary>
    public static string HumanizeNumber(int number)
    {
        if (number > 100000000)
        {
            return string.Format("{0}{1}", number / 100000000, "亿");
        }
        else if (number > 10000000)
        {
            return string.Format("{0}{1}", number / 10000000, "千万");
        }
        else if (number > 1000000)
        {
            return string.Format("{0}{1}", number / 1000000, "百万");
        }
        else if (number > 10000)
        {
            return string.Format("{0}{1}", number / 10000, "万");
        }

        return number.ToString();
    }

    /// <summary>
    /// 获取从父节点到自己的完整路径
    /// </summary>
    public static string GetRootPathName(UnityEngine.Transform transform)
    {
        var pathName = "/" + transform.name;
        while (transform.parent != null)
        {
            transform = transform.parent;
            pathName += "/" + transform.name;
        }
        return pathName;
    }

    /// <summary>
    /// 获取指定流的MD5
    /// </summary>
    public static string MD5_Stream(Stream stream)
    {
        System.Security.Cryptography.MD5CryptoServiceProvider get_md5 =
            new System.Security.Cryptography.MD5CryptoServiceProvider();

        byte[] hash_byte = get_md5.ComputeHash(stream);

        string resule = System.BitConverter.ToString(hash_byte);

        resule = resule.Replace("-", "");

        return resule;
    }

    public static string MD5_File(string filePath)
    {
        try
        {
            using (FileStream get_file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                return MD5_Stream(get_file);
            }
        }
        catch (Exception e)
        {
            return e.ToString();
        }
    }

    public static byte[] MD5_bytes(string str)
    {
        // MD5 文件名
        var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
        return md5.ComputeHash(System.Text.Encoding.Unicode.GetBytes(str));
    }

    /// 字符串16 MD5
    public static string MD5_16bit(string str)
    {
        byte[] md5bytes = MD5_bytes(str);
        str = System.BitConverter.ToString(md5bytes, 4, 8);
        str = str.Replace("-", "");
        return str;
    }

    /// <summary>
    /// 判断字符串是否是数字
    /// </summary>
    public static bool IsNumber(string str)
    {
        if (string.IsNullOrEmpty(str))
        {
            // 传入的值为空
            return false;
        }
        var pattern = @"^\d*$";
        return System.Text.RegularExpressions.Regex.IsMatch(str, pattern);
    }
}