Common通用函数,包含大量常用处理函数的集合

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;

namespace Common
{
    public static class Get
    {
        public class Singleton : MonoBehaviour where T : Component
        {
            static T _this;
            public static T This { get { return _this == default(T) ? FindObjectOfType() : _this; } }
        }
        public static UIRoot UiRoot { get { return Object.FindObjectOfType(); } }
        public static Camera UiCamera { get { return Object.FindObjectOfType().transform.Find("Camera").GetComponent(); } }
        public static int MaxDepth
        {
            get
            {
                var widgets = Object.FindObjectsOfType();
                var maxDepth = widgets.Length == 0 ? 0 : widgets.Max(t => t.depth);
                return maxDepth;
            }
        }
        public static int DefaultLayer { get { return 8; } }
        public static string DefaultLayerName { get { return LayerMask.LayerToName(DefaultLayer); } }
        public static string Time(float totalTime)
        {
            var time = string.Empty;
            var hour = Mathf.Floor(totalTime / 3600);
            var min = Mathf.Floor(totalTime % 3600 / 60);
            var sec = Mathf.Floor(totalTime % 60);
            time = hour >= 0 && hour < 10 ? string.Concat("0", hour, ":") : string.Concat(hour, ":");
            time = min >= 0 && min < 10 ? string.Concat(time, "0", min, ":") : string.Concat(time, min, ":");
            time = sec >= 0 && sec < 10 ? string.Concat(time, "0", sec) : string.Concat(time, sec);
            return time;
        }
        public static Vector3 ScreenLocation(Vector2 location)
        {
            var worldPosition = UiCamera.ScreenToWorldPoint(new Vector3(location.x, location.y, 0f));
            var screenPosition = UiCamera.transform.InverseTransformPoint(worldPosition);
            return screenPosition;
        }
        public static Vector3 AngleToAxis(float angle)
        {
            var x = Mathf.Sin(angle * Mathf.Deg2Rad);
            var y = Mathf.Cos(angle * Mathf.Deg2Rad);
            return new Vector3(x, y);
        }
        public static float AxisToAngle(Vector3 axis)
        {
            var a = Mathf.Atan2(axis.x, axis.y) / Mathf.Deg2Rad;
            return a < 0 ? 360 + a : a;
        }
        public static float AngleBetweenAxis(Vector3 axis1, Vector3 axis2, bool isClockwise = false, bool isJustOneside = false)
        {
            var cross = Vector3.Cross(axis1, axis2);
            var angle = Vector3.Angle(axis1, axis2);
            var round = isJustOneside ? 0 : 360;
            var deg360 = 0.0f;
            if (isClockwise)
            {
                deg360 = cross.z > 0 ? angle : round - angle;
            }
            else
            {
                deg360 = cross.z < 0 ? angle : round - angle;
            }
            return deg360;
        }
        public static Vector2 OvalAxis(Vector2 axis, float a, float b, bool isClockwise = false)
        {
            var cross = Vector3.Cross(axis, Vector2.right);
            var angle = Vector2.Angle(axis, Vector2.right);
            var deg360 = 0.0f;
            if (isClockwise)
            {
                deg360 = cross.z > 0 ? angle : 360 - angle;
            }
            else
            {
                deg360 = cross.z < 0 ? angle : 360 - angle;
            }
            var t = deg360 * Mathf.Deg2Rad;
            var bcost = b * Mathf.Cos(t);
            var asint = a * Mathf.Sin(t);
            var bcostp2 = Mathf.Pow(bcost, 2);
            var asintp2 = Mathf.Pow(asint, 2);
            var sqrt = Mathf.Sqrt(bcostp2 + asintp2);
            var r = a * b / sqrt;
            var x = r * Mathf.Cos(t);
            var y = r * Mathf.Sin(t);
            var v = new Vector2(x, y);
            return v;
        }
        public static float OvalValueX(float y, float a, float b, bool isOnlyPositive = false)
        {
            var ypow2 = Mathf.Pow(y, 2);
            var bpow2 = Mathf.Pow(b, 2);
            var tmp = 1 - ypow2 / bpow2;
            var abs = isOnlyPositive ? Mathf.Abs(tmp) : tmp;
            var sqrt = Mathf.Sqrt(abs);
            var x = a * sqrt;
            return x;
        }
        public static float OvalValueY(float x, float a, float b, bool isOnlyPositive = false)
        {
            var xpow2 = Mathf.Pow(x, 2);
            var apow2 = Mathf.Pow(a, 2);
            var tmp = 1 - xpow2 / apow2;
            var abs = isOnlyPositive ? Mathf.Abs(tmp) : tmp;
            var sqrt = Mathf.Sqrt(abs);
            var y = b * sqrt;
            return y;
        }
        public static string LastSpriteName(UIAtlas atlas, int index)
        {
            var count = atlas.spriteList.Count;
            index = Mathf.Abs(index);
            index = --index % count;
            index = index < 0 ? count - 1 : index;
            return atlas.spriteList[index].name;
        }
        public static string NextSpriteName(UIAtlas atlas, int index)
        {
            var count = atlas.spriteList.Count;
            index = Mathf.Abs(index);
            index = ++index % count;
            return atlas.spriteList[index].name;
        }
        public static string ByteToString(byte[] byt) { return Encoding.UTF8.GetString(byt); }
        public static byte[] StringToByte(string str) { return Encoding.UTF8.GetBytes(str); }
        public static TKey DictionaryKeyByIndex(Dictionary dic, int index)
        {
            var res = default(TKey);
            try
            {
                res = dic.Keys.ToArray()[index];
            }
            catch
            {
                // ignored
            }
            return res;
        }
        public static TValue DictionaryValueByIndex(Dictionary dic, int index)
        {
            var res = default(TValue);
            try
            {
                res = dic.Values.ToArray()[index];
            }
            catch
            {
                // ignored
            }
            return res;
        }
    }

    public static class Do
    {
        static int FitSize(float val)
        {
            var zoomRatio = (float)Get.UiRoot.activeHeight / Screen.height;
            return Mathf.CeilToInt(val * zoomRatio);
        }
        public static void Stretching(UIWidget target)
        {
            var scaleX = FitSize(Screen.width) / (float)target.width;
            var scaleY = FitSize(Screen.height) / (float)target.height;
            target.transform.localScale = new Vector2(scaleX, scaleY);
        }
        public static void AdjustPanel(Component parent, UIWidget baseplate, bool isAvoidIterative = true)
        {
            var ratioX = FitSize(Screen.width) / (float)baseplate.width;
            var ratioY = FitSize(Screen.height) / (float)baseplate.height;
            var min = Mathf.Min(ratioX, ratioY);
            var scale = new Vector3(min, min, 0);
            var list = parent.GetComponentsInChildren();
            foreach (var children in list.Where(children => !children.transform.localScale.Equals(scale)).Where(children => !isAvoidIterative || children.parent.GetInstanceID() == parent.GetInstanceID()))
            {
                children.transform.localScale = scale;
                var x = children.transform.localPosition.x;
                var y = children.transform.localPosition.y;
                children.transform.localPosition = new Vector3(x * min, y * min, 0);
            }
        }
        public static void ResizeChildren(Component parent, float scale)
        {
            var scaleAxis = new Vector3(scale, scale, 0);
            var list = parent.GetComponentsInChildren();
            foreach (var children in list.Where(children => !children.localScale.Equals(scaleAxis)).Where(children => children.parent.GetInstanceID() == parent.GetInstanceID()))
            {
                children.localScale = scaleAxis;
                var x = children.localPosition.x;
                var y = children.localPosition.y;
                children.localPosition = new Vector3(x * scale, y * scale, 0);
            }
        }
        public static void ChangeScene(Option.Scene sceneName)
        {
            SceneManager.LoadScene((int)sceneName);
            Resources.UnloadUnusedAssets();//释放无用资源
        }
        public static Vector3 MoveToScreenLocation(Transform target, Vector3 location)
        {
            //变换屏幕坐标到世界坐标
            if (Get.UiCamera.orthographic)
            {
                location.x = Mathf.Round(location.x);
                location.y = Mathf.Round(location.y);
                location.z = Mathf.Round(location.z);
            }
            location = Get.UiCamera.ScreenToWorldPoint(location);
            if (!Get.UiCamera.orthographic || target.parent == default(Transform)) return location;
            //变换父级(ngui)坐标到世界坐标
            location = target.parent.InverseTransformPoint(location);
            location.x = Mathf.RoundToInt(location.x);
            location.y = Mathf.RoundToInt(location.y);
            location.z = Mathf.RoundToInt(location.z);
            return location;
        }
        public static void TagSync(List tags)
        {
            foreach (var t in tags)
            {
#if UNITY_EDITOR
                UnityEditorInternal.InternalEditorUtility.AddTag(t);
#endif
            }
        }
        public static void ZoomWidget(ref T widget, float expectSize) where T : UIWidget
        {
            widget.MakePixelPerfect();
            var scaleX = widget.width / expectSize;
            var scaleY = widget.height / expectSize;
            var scale = Mathf.Max(scaleX, scaleY);
            widget.width = Mathf.CeilToInt(widget.width / scale);
            widget.height = Mathf.CeilToInt(widget.height / scale);
        }
        public static void CleanUpComponent(GameObject obj) where T : Component
        {
            foreach (var children in obj.GetComponentsInChildren())
            {
                Object.DestroyObject(children);
            }
        }
        public static void AddListenerOnClick(T widget, UIEventListener.VoidDelegate onClick, Vector2 size = default(Vector2)) where T : UIWidget
        {
            var boxCollider = widget.gameObject.AddMissingComponent();
            if (size == Vector2.zero || size == default(Vector2))
            {
                widget.autoResizeBoxCollider = true;
                widget.MakePixelPerfect();
            }
            else
            {
                widget.autoResizeBoxCollider = false;
                boxCollider.size = size;
            }
            UIEventListener.Get(widget.gameObject).onClick = onClick;
        }
    }

    public static class New
    {
        public static GameObject Obj(string objName, Transform parent, Vector3 position = default(Vector3))
        {
            var obj = new GameObject
            {
                name = objName,
                tag = parent.tag,
                layer = parent.gameObject.layer
            };
            obj.transform.SetParent(parent);
            obj.transform.localEulerAngles = Vector3.zero;
            obj.transform.localPosition = position;
            obj.transform.localRotation = Quaternion.identity;
            obj.transform.localScale = Vector3.one;
            return obj;
        }
        public static T Component(string objName, Transform parent, Vector3 position = default(Vector3)) where T : Component
        {
            var obj = new GameObject
            {
                name = objName,
                tag = parent.tag,
                layer = parent.gameObject.layer
            };
            obj.transform.SetParent(parent);
            obj.transform.localEulerAngles = Vector3.zero;
            obj.transform.localPosition = position;
            obj.transform.localRotation = Quaternion.identity;
            obj.transform.localScale = Vector3.one;
            return obj.AddComponent();
        }
        public static GameObject AnimationObject(string objName, Transform parent, Vector2 position, UIAtlas atlas, string spriteName, int depth, Vector2 size, string namePrefix, int framesPerSecond, bool isLoop = true)
        {
            var obj = new GameObject
            {
                name = objName,
                tag = parent.tag,
                layer = parent.gameObject.layer
            };
            obj.transform.SetParent(parent);
            obj.transform.localEulerAngles = Vector3.zero;
            obj.transform.localPosition = position;
            obj.transform.localRotation = Quaternion.identity;
            obj.transform.localScale = Vector3.one;
            var sprite = obj.AddComponent();
            sprite.atlas = atlas;
            sprite.spriteName = spriteName;
            sprite.depth = depth;
            var widget = obj.AddComponent();
            if (size == Vector2.zero)
            {
                sprite.MakePixelPerfect();
                widget.width = sprite.width;
                widget.height = sprite.height;
            }
            else
            {
                widget.width = size.x;
                widget.height = size.y;
            }
            var spriteAnimation = obj.AddComponent();
            spriteAnimation.namePrefix = namePrefix;
            spriteAnimation.framesPerSecond = framesPerSecond;
            spriteAnimation.loop = isLoop;
            return obj;
        }
    }

    public static class Read
    {
        public static List CsvFile(string filePath, out bool isDone)
        {
            var records = new List();
            using (var reader = new StreamReader(filePath, Encoding.UTF8))
            {
                isDone = false;
                while (reader.Peek() != -1)
                {
                    var line = reader.ReadLine();
                    var data = new List();
                    var str = string.Empty;
                    var n = 0;
                    foreach (var piece in line.Split(','))
                    {
                        if (!piece.Contains('\"'))
                        {
                            data.Add(piece);
                        }
                        else
                        {
                            n++;
                            str += piece + ",";
                        }
                        if (n == 0 || n % 2 != 0 || str == null) continue;
                        data.Add(str.Trim('\"', ','));
                        str = null;
                    }
                    records.Add(data.ToArray());
                }
                reader.Close();
                isDone = true;
            }
            return records;
        }
        public static List CsvFile(TextReader tr, out bool isDone)
        {
            var records = new List();
            using (var reader = tr)
            {
                isDone = false;
                while (reader.Peek() != -1)
                {
                    var line = reader.ReadLine();
                    var data = new List();
                    var str = string.Empty;
                    var n = 0;
                    foreach (var piece in line.Split(','))
                    {
                        if (!piece.Contains('\"'))
                        {
                            data.Add(piece);
                        }
                        else
                        {
                            n++;
                            str += piece + ",";
                        }
                        if (n == 0 || n % 2 != 0 || str == null) continue;
                        data.Add(str.Trim('\"', ','));
                        str = null;
                    }
                    records.Add(data.ToArray());
                }
                reader.Close();
                isDone = true;
            }
            return records;
        }
    }

}

你可能感兴趣的:(C#样例,unity3D)