Unity脚本C# Util(常用类)及GPSUtil

5 篇文章 0 订阅

一、unity中比较常用的方法

(直接封装成一个类,需要时调用即可)

using UnityEngine;
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

public class Util {

    private static List<string> luaPaths = new List<string>();
	// 对象转整型
    public static int Int(object o)
    {
        return Convert.ToInt32(o);
    }
	// 对象转32 位单精度浮点型
    public static float Float(object o)
    {
        return (float)Math.Round(Convert.ToSingle(o), 2);
    }
	// 对象转64 位有符号整数类型
    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);
    }
	// uId
    public static string Uid(string uid)
    {
        int position = uid.LastIndexOf('_');
        return uid.Remove(0, position + 1);
    }
	// 获取时间
    public static long GetTime()
    {
        //Debug.LogError(DateTime.UtcNow.Ticks);
        //Debug.LogError(DateTime.UtcNow.Add(AppConst.ServerTimeSpan).Ticks);
        TimeSpan ts = new TimeSpan(DateTime.UtcNow.Add(AppConst.ServerTimeSpan).Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks);
        return (long)ts.TotalMilliseconds;
    }

    // 隐藏用户ID为6位+两位**
    public static String ReBuildUserId(string mineId , string userId)
    {
        if (userId.Length == 8)
        {
            if (userId != mineId)
            {
                userId = userId.Substring(0, 6) + "**";
            }
        }
        return userId;
    }

    /// <summary> 
    /// 获取时间戳 
    /// </summary> 
    /// <returns></returns> 
    public static string GetTimeStamp()
    {
        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        return Convert.ToInt64(ts.TotalSeconds).ToString();
    }
    public static DateTime TransfromTime(long time)
    {
        DateTime dt197011 = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
        long lsystemTime = long.Parse(time + "0000000");
        TimeSpan toNowTs = new TimeSpan(lsystemTime);
        return dt197011.Add(toNowTs);
    }
    /// <summary>
    /// 搜索子物体组件-GameObject版
    /// </summary>
    public static T Get<T>(GameObject go, string subnode) where T : Component
    {
        if (go != null)
        {
            Transform sub = go.transform.Find(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.Find(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.Find(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>
    /// 查找子对象
    /// </summary>
    public static GameObject Child(GameObject go, string subnode)
    {
        return Child(go.transform, subnode);
    }

    /// <summary>
    /// 查找子对象
    /// </summary>
    public static GameObject Child(Transform go, string subnode)
    {
        Transform tran = go.Find(subnode);
        if (tran == null) return null;
        return tran.gameObject;
    }

    /// <summary>
    /// 取平级对象
    /// </summary>
    public static GameObject Peer(GameObject go, string subnode)
    {
        return Peer(go.transform, subnode);
    }

    /// <summary>
    /// 取平级对象
    /// </summary>
    public static GameObject Peer(Transform go, string subnode)
    {
        Transform tran = go.parent.Find(subnode);
        if (tran == null) return null;
        return tran.gameObject;
    }

    /// <summary>
    /// 计算字符串的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>
    /// 计算文件的MD5值
    /// </summary>
    public static string md5file(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);
        }
    }

    /// <summary>
    /// 清除所有子节点
    /// </summary>
    public static void ClearChild(Transform go)
    {
        if (go == null) return;
        for (int i = go.childCount - 1; i >= 0; i--)
        {
            GameObject.DestroyImmediate(go.GetChild(i).gameObject);
        }
    }
    /// <summary>
    /// 清除所有iTween
    /// </summary>
    /// <param name="obj"></param>
    public static void ClearItweens(GameObject obj)
    {
        iTween[] itweens = obj.GetComponents<iTween>();
        int i = 0;
        for (i = 0; i < itweens.Length; i++)
        {
            GameObject.DestroyImmediate(itweens[i]);
        }
    }

    /// <summary>
    /// 清理内存
    /// </summary>
    public static void ClearMemory()
    {
        GC.Collect(); 
        Resources.UnloadUnusedAssets();
        //LuaManager mgr = AppFacade.Instance.GetManager<LuaManager>(ManagerName.Lua);
        //if (mgr != null) mgr.LuaGC();
    }

    /// <summary>
    /// 取得数据存放目录
    /// </summary>
    public static string DataPath
    {
        get
        {
            string game = AppConst.APP_NAME.ToLower();
            if (Application.isMobilePlatform)
            {
                //移动设备路径
                return Application.persistentDataPath + "/" + game + "/";
            }
            //if (AppConst.DEBUG_MODE)
            //{
            //    return Application.dataPath + "/StreamingAssets/";
            //}
            if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer)
            {
                //Window编辑器
                return Application.dataPath + "/StreamingAssets/";
            }
            if (Application.platform == RuntimePlatform.OSXEditor)
            {
                //int i = Application.dataPath.LastIndexOf('/');
                //return Application.dataPath.Substring(0, i + 1) + game + "/";
                return Application.dataPath + "/StreamingAssets/";
            }
            return "c:/" + game + "/";
        }
    }

    /// <summary>
    /// 获取AssetBundle包目录
    /// </summary>
    /// <returns></returns>
    public static string GetAssetBundlePath()
    {
        return DataPath + AppConst.ASSETBUNDLE_MANIFEST + "/";
    }
    /// <summary>
    /// 获取AssetBundle的资源包含xml文件
    /// </summary>
    /// <returns></returns>
    public static string GetAssetBundleXmlPath()
    {
        return DataPath + AppConst.ASSETBUNDLE_XML;
    }

    public static string GetRelativePath()
    {
        if (Application.isEditor)
            return "file://" + System.Environment.CurrentDirectory.Replace("\\", "/") + "/Assets/StreamingAssets/" + AppConst.ASSETBUNDLE_MANIFEST + "/";
        else if (Application.isMobilePlatform || Application.isConsolePlatform)
            return Application.streamingAssetsPath + "/" + AppConst.ASSETBUNDLE_MANIFEST + "/";
        else // For standalone player.
            return "file://" + Application.streamingAssetsPath + "/";
    }

    /// <summary>
    /// 取得行文本
    /// </summary>
    public static string GetFileText(string path)
    {
        return File.ReadAllText(path);
    }

    /// <summary>
    /// 网络可用
    /// </summary>
    public static bool NetAvailable
    {
        get
        {
            return Application.internetReachability != NetworkReachability.NotReachable;
        }
    }

    /// <summary>
    /// 是否是无线
    /// </summary>
    public static bool IsWifi
    {
        get
        {
            return Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork;
        }
    }

    /// <summary>
    /// 应用程序内容路径
    /// </summary>
    public static string AppContentPath()
    {
        string path = string.Empty;
        switch (Application.platform)
        {
            case RuntimePlatform.Android:
                //path = "jar:file://" + Application.dataPath + "!/assets/";
                //break;
            case RuntimePlatform.IPhonePlayer:
                //path = Application.dataPath + "/Raw/";
                path = Application.streamingAssetsPath;
                break;
            default:
                path = Application.dataPath + "/StreamingAssets/";
                break;
        }
        return path;
    }

    public static string ScreenCapurePath()
    {
        return DataPath + "/Screenshot.jpg";
    }

    #region 保存存档

    /// <summary>
    /// 生成一个Key名
    /// </summary>
    public static string GetKey(string key)
    {
        return AppConst.APP_NAME + "_" + key;
    }

    /// <summary>
    /// 取得整型
    /// </summary>
    public static int GetInt(string key)
    {
        string name = GetKey(key);
        return PlayerPrefs.GetInt(name, 0);
    }
    public static int GetInt(string key, int def)
    {
        string name = GetKey(key);
        return PlayerPrefs.GetInt(name, def);
    }

    /// <summary>
    /// 有没有值
    /// </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>
    /// 取得数据
    /// </summary>
    public static string GetString(string key)
    {
        string name = GetKey(key);
        return PlayerPrefs.GetString(name, "");
    }

    public static string GetString(string key, string defaultValue)
    {
        string name = GetKey(key);
        return PlayerPrefs.GetString(name, defaultValue);
    }

    /// <summary>
    /// 保存数据(用于缓存)
    /// </summary>
    public static void SetString(string key, string value)
    {
        string name = GetKey(key);
        PlayerPrefs.DeleteKey(name);
        PlayerPrefs.SetString(name, value);
    }

    public static float GetFloat(string key)
    {
        string name = GetKey(key);
        //return float.Parse(PlayerPrefs.GetString(name));
        return PlayerPrefs.GetFloat(name);
    }

    public static void SetFloat(string key, float value)
    {
        string name = GetKey(key);
        PlayerPrefs.DeleteKey(name);
        //PlayerPrefs.SetString(name, value.ToString("0.00"));
        PlayerPrefs.SetFloat(name, value);
    }

    /// <summary>
    /// 删除数据
    /// </summary>
    public static void RemoveData(string key)
    {
        string name = GetKey(key);
        PlayerPrefs.DeleteKey(name);
    }

    public static void SaveData()
    {
        PlayerPrefs.Save();
    }

    #endregion

    #region Base64

    /// <summary>
    /// Base64编码
    /// </summary>
    public static string Encode(string message)
    {
        byte[] bytes = Encoding.GetEncoding("utf-8").GetBytes(message);
        return Convert.ToBase64String(bytes);
    }

    /// <summary>
    /// Base64解码
    /// </summary>
    public static string Decode(string message)
    {
        byte[] bytes = Convert.FromBase64String(message);
        return Encoding.GetEncoding("utf-8").GetString(bytes);
    }

    public static string EncodeByte(byte[] data)
    {
        return Convert.ToBase64String(data);
    }

    public static byte[] DecodeByte(string data)
    {
        return Convert.FromBase64String(data);
    }

    #endregion

    #region 图片
    /// <summary>
    /// 截屏
    /// </summary>
    public static void ScreenCapure()
    {
        int width = Screen.width;
        int height = Screen.height;
        //修改图片尺寸
        float ratio = (float)((width * 1.0) / height);
        height = 640;
        width = (int)(height * ratio);
        Debug.Log(width + " / " + height);
        // 创建一个RenderTexture对象  
        RenderTexture rt = new RenderTexture(width, height, 0);
        // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机  
        Camera camera = GameObject.Find("Camera").GetComponent<Camera>();
        camera.targetTexture = rt;
        camera.Render();

        // 激活这个rt, 并从中中读取像素。  
        RenderTexture.active = rt;
        Texture2D screenShot = new Texture2D(width, height, TextureFormat.RGB24, false);
        screenShot.ReadPixels(new Rect(0, 0, width, height), 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素  
        screenShot.Apply();

        // 重置相关参数,以使用camera继续在屏幕上显示  
        camera.targetTexture = null;
        RenderTexture.active = null; // JC: added to avoid errors  
        GameObject.Destroy(rt);
        // 最后将这些纹理数据,成一个png图片文件  
        byte[] bytes = screenShot.EncodeToJPG();
        screenShot.Compress(false);
        string filename = ScreenCapurePath();
        System.IO.File.WriteAllBytes(filename, bytes);
    }
    /// <summary>
    /// 截屏
    /// </summary>
    /// <param name="mCamera">指定相机</param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    public static void ScreenCapure(Camera mCamera, int width, int height)
    {
        RenderTexture rt = new RenderTexture(width, height, 0);
        // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机  
        mCamera.targetTexture = rt;
        mCamera.Render();

        // 激活这个rt, 并从中中读取像素。  
        RenderTexture.active = rt;
        Texture2D screenShot = new Texture2D(width, height, TextureFormat.RGB24, false);
        screenShot.ReadPixels(new Rect(0, 0, width, height), 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素  
        screenShot.Apply();

        // 重置相关参数,以使用camera继续在屏幕上显示  
        mCamera.targetTexture = null;
        RenderTexture.active = null; // JC: added to avoid errors  
        GameObject.Destroy(rt);
        // 最后将这些纹理数据,成一个jpg图片文件  
        byte[] bytes = screenShot.EncodeToJPG();
        screenShot.Compress(false);
        string filename = ScreenCapurePath();
        Debug.Log(filename);
        System.IO.File.WriteAllBytes(filename, bytes);
    }
    /// <summary>
    /// 截屏
    /// </summary>
    public static void ScreenCapure(string path)
    {
        int width = Screen.width;
        int height = Screen.height;
        //修改图片尺寸
        float ratio = (float)((width * 1.0) / height);
        height = 640;
        width = (int)(height * ratio);
        Debug.Log(width + " / " + height);
        // 创建一个RenderTexture对象  
        RenderTexture rt = new RenderTexture(width, height, 0);
        // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机  
        Camera camera = GameObject.Find("Camera").GetComponent<Camera>();
        camera.targetTexture = rt;
        camera.Render();

        // 激活这个rt, 并从中中读取像素。  
        RenderTexture.active = rt;
        Texture2D screenShot = new Texture2D(width, height, TextureFormat.RGB24, false);
        screenShot.ReadPixels(new Rect(0, 0, width, height), 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素  
        screenShot.Apply();

        // 重置相关参数,以使用camera继续在屏幕上显示  
        camera.targetTexture = null;
        RenderTexture.active = null; // JC: added to avoid errors  
        GameObject.Destroy(rt);
        // 最后将这些纹理数据,成一个png图片文件  
        byte[] bytes = screenShot.EncodeToJPG();
        screenShot.Compress(false);
        string filename = ScreenCapurePath();
        Debug.Log(path);
        System.IO.File.WriteAllBytes(path, bytes);
    }
    /// <summary>
    /// 删除截屏文件
    /// </summary>
    public static void ClearScreenCapure()
    {
        if (File.Exists(ScreenCapurePath()))
            File.Delete(ScreenCapurePath());
    }

    public static Sprite GetSpriteFromByte(byte[] data)
    {
        Texture2D texture = new Texture2D(144, 113);
        texture.LoadImage(data);
        Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
        return sprite;
    }
    public static Sprite GetSpriteFromByte(string data)
    {
        byte[] bytes = DecodeByte(data);
        return GetSpriteFromByte(bytes);
    }

    public static Sprite GetSpriteFromTexture(Texture tex)
    {
        Texture2D texture = tex as Texture2D;
        Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
        return sprite;
    }

    #endregion

    /// <summary>
    /// 手机震动
    /// </summary>
    public static void Vibrate()
    {
#if UNITY_ANDROID
        Handheld.Vibrate();
#elif UNITY_IOS
		Handheld.Vibrate(); 
#else
#endif
    }

    private const double EARTH_RADIUS = 6378.137;//地球半径
    private static double rad(double d)
    {
        return d * Math.PI / 180.0;
    }

    /// <summary>
    /// 获得经纬度距离
    /// </summary>
    /// <param name="lat1"></param>
    /// <param name="lng1"></param>
    /// <param name="lat2"></param>
    /// <param name="lng2"></param>
    /// <returns>单位米</returns>
    public static int GetDistance(double lat1, double lng1, double lat2, double lng2)
    {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);

        double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) +
         Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.Round(s * 10000) / 10;

        return (int)s;
    }

    public static string NumberToChinese(string numberStr)
    {
        string numStr = "0123456789";
        string chineseStr = "零一二三四五六七八九";
        char[] c = numberStr.ToCharArray();
        char[] target = numberStr.ToCharArray();
        int intNumber = int.Parse(numberStr);
        if (intNumber > 10 && intNumber % 10 == 0)
        {
            target = new char[2];
            target[1] = '十';
            int index = numStr.IndexOf(c[0]);
            target[0] = chineseStr.ToCharArray()[index];
        }
        else if (intNumber > 20)
        {
            target = new char[3];
            target[1] = '十';
            for (int i = 0; i < c.Length; i++)
            {
                int index = numStr.IndexOf(c[i]);
                if (index != -1)
                {
                    if (i == 0)
                        target[0] = chineseStr.ToCharArray()[index];
                    else
                        target[2] = chineseStr.ToCharArray()[index];
                }
            }
        }
        else if (intNumber == 10)
        {
            return "十";
        }
        else if (intNumber > 10)
        {
            target[0] = '十';
            for (int i = 1; i < c.Length; i++)
            {
                int index = numStr.IndexOf(c[i]);
                if (index != -1)
                    target[i] = chineseStr.ToCharArray()[index];
            }
        }
        else
        {
            for (int i = 0; i < c.Length; i++)
            {
                int index = numStr.IndexOf(c[i]);
                if (index != -1)
                    target[i] = chineseStr.ToCharArray()[index];
            }
        }
        numStr = null;
        chineseStr = null;
        return new string(target);
    }

    /// <summary>
    /// 随机字符方法一 遍历返回
    /// </summary>
    /// <param name="chars">随机字符串源</param>
    /// <param name="length">返回随机的字符串个数</param>
    /// <returns></returns>
    public static string Radomstrs(int length)
    {
        string chars = "ABCDEFGHIJKLMNOPQRSTUWVXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        string strs = string.Empty;
        System.Random random = new System.Random();
        for (int i = 0; i < length; i++)
        {
            strs += chars[random.Next(chars.Length)];
        }
        return strs;
    }

    /// <summary>
    /// 获取当前时间戳
    /// </summary>
    /// <param name="bflag"></param>
    /// <returns></returns>
    public static long GetNowDateTime(bool bflag = true)
    {
        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0);
        long ret;
        if (bflag)
            ret = Convert.ToInt64(ts.TotalSeconds);
        else
            ret = Convert.ToInt64(ts.TotalMilliseconds);
        return ret;

    }
}

二、GPSUtil.cs

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class GPSUtil : MonoBehaviour
{

    public Text txt;

    public void GetGPS()
    {
        StartCoroutine(StartGPS());
    }

    IEnumerator StartGPS()
    {
        txt.text = "开始获取GPS信息";

        // 检查位置服务是否可用  
        if (!Input.location.isEnabledByUser)
        {
            txt.text = "位置服务不可用";
            yield break;
        }

        // 查询位置之前先开启位置服务  
        txt.text = "启动位置服务";
        Input.location.Start();

        // 等待服务初始化  
        int maxWait = 20;
        while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
        {
            txt.text = Input.location.status.ToString() + ">>>" + maxWait.ToString();
            yield return new WaitForSeconds(1);
            maxWait--;
        }

        // 服务初始化超时  
        if (maxWait < 1)
        {
            txt.text = "服务初始化超时";
            yield break;
        }

        // 连接失败  
        if (Input.location.status == LocationServiceStatus.Failed)
        {
            txt.text = "无法确定设备位置";
            yield break;
        }
        else
        {
            txt.text = "Location: rn" +
            "纬度:" + Input.location.lastData.latitude + "rn" +
            "经度:" + Input.location.lastData.longitude + "rn" +
            "海拔:" + Input.location.lastData.altitude + "rn" +
            "水平精度:" + Input.location.lastData.horizontalAccuracy + "rn" +
            "垂直精度:" + Input.location.lastData.verticalAccuracy + "rn" +
            "时间戳:" + Input.location.lastData.timestamp;
        }

        // 停止服务,如果没必要继续更新位置,(为了省电)  
        Input.location.Stop();
    }
}

封装成一个方法,方便调用,也可减少多余代。手机震动及截图,打包后在手机上操作,还是可以的。等有空再发布一下效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值