Utils.cs 12.5 KB
Newer Older
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
/*
 *Copyright(C) 2020 by  GYYX All rights reserved.
 *Unity版本:2018.4.36f1 
 *作者:Chief  
 *创建日期: 2022-01-04 
 *模块说明:
 *版本: 1.2
*/

using System.Collections.Generic;
using Unity.Collections;
using UnityEngine;

namespace Oroxylum
{

    /// <summary>
    /// 通用工具;
    /// </summary>
    public static class Utils
    {
        #region 组件相关

        public static GameObject CreateGameObjectAtPath(string path)
        {
            if (string.IsNullOrEmpty(path))
                return null;

            var obj = GameObject.Find(path);
            if (obj == null)
            {
                //在最近父节点进行创建;
                var index = path.LastIndexOf('/');
                if (index == -1)
                    return new GameObject(path);

                var parentPath = path.Substring(0, index);
                var selftPath = path.Substring(index + 1);

                obj = new GameObject(selftPath);

                var parent = CreateGameObjectAtPath(parentPath);
                if (parent != null)
                    obj.transform.parent = parent.transform;

                obj.NormalizeGameObject();
            }

            return obj;
        }

        public static Transform CreateTransformAtParent(string name, Transform parentTrans)
        {
            var go = new GameObject(name);
            go.SetParent(parentTrans);
            go.NormalizeGameObject();
            return go.transform;
        }

        public static Transform CreateChild(this Transform parentTrans, string name)
        {
            var go = new GameObject(name);
            go.SetParent(parentTrans);
            go.NormalizeGameObject();
            return go.transform;
        }

        public static void NormalizeGameObject(this GameObject target)
        {
            target.transform.localPosition = Vector3.zero;
            target.transform.localRotation = Quaternion.identity;
            target.transform.localScale = Vector3.one;
        }

        [System.Obsolete("使用 SetActiveSafe 替换。")]
        public static void SetActive2(this GameObject obj, bool active) { obj.SetActiveSafe(active); }

        public static void SetActiveSafe(this GameObject obj, bool active)
        {
            if (obj == null)
                return;

            if (obj.activeSelf == active)
                return;

            obj.SetActive(active);
        }

        [System.Obsolete("使用 SetActiveSafe 替换。")]
        public static void SetActive2(this Component compT, bool active) { compT.SetActiveSafe(active); }

        public static void SetActiveSafe(this Component compT, bool active)
        {
            if (compT == null)
                return;

            compT.gameObject.SetActiveSafe(active);
        }

        public static void Destory(this UnityEngine.Object obj)
        {
            if (obj == null)
                return;

            //特殊:于Transform的判定;
            if (obj is Transform)
                (obj as Transform).gameObject.Destory();

#if UNITY_EDITOR
            if (!Application.isPlaying)
                UnityEngine.Object.DestroyImmediate(obj);
            else
#endif
                UnityEngine.Object.Destroy(obj);
        }

        /// <summary>
        /// 获取层级名;
        /// </summary>
        public static string GetHierarchyName(this Transform trans)
        {
            if (trans == null)
                return null;

            string name = trans.name;
            var parent = trans.parent;
            while (parent != null)
            {
                name = $"{parent.name}/{name}";
                parent = parent.parent;
            }
            return name;
        }

        /// <summary>
        /// 获取根节点
        /// </summary>
        /// <returns></returns>
        public static Transform GetRootTransform(this Transform trans)
        {
            if (trans == null)
                return null;
            if (trans.parent == null)
                return trans;
            return trans.parent.GetRootTransform();
        }

        /// <summary>
        /// 获取,或者添加一个组件;
        /// </summary>
        public static T GetOrAddComponent<T>(this GameObject obj) where T : Component
        {
            if (obj == null)
                return null;

            var compt = obj.GetComponent<T>();
            if (compt == null)
                compt = obj.AddComponent<T>();
            return compt;
        }

        /// <summary>
        /// 获取,或者添加一个组件;
        /// </summary>
        public static T GetOrAddComponent<T>(this Transform trans) where T : Component
        {
            if (trans == null)
                return null;
            return trans.gameObject.GetOrAddComponent<T>();
        }

        /// <summary>
        /// 获取,或者添加一个组件;
        /// </summary>
        public static T GetOrAddComponent<T>(this Component compt) where T : Component
        {
            if (compt == null)
                return null;
            return compt.gameObject.GetOrAddComponent<T>();
        }

        #endregion

        #region 扩展方法

        public static void AddOrReplace<T1, T2>(this Dictionary<T1, T2> dict, T1 key, T2 val)
        {
            if (dict == null)
                return;

            if (key == null || val == null)
                return;

            if (dict.ContainsKey(key))
                dict[key] = val;
            else
                dict.Add(key, val);
        }

        public static void AddOrIngore<T1, T2>(this Dictionary<T1, T2> dict, T1 key, T2 val)
        {
            if (dict == null)
                return;

            if (key == null || val == null)
                return;

            if (dict.ContainsKey(key))
                return;
            else
                dict.Add(key, val);
        }

        public static T2 GetValue<T1, T2>(this Dictionary<T1, T2> dict, T1 key)
        {
            if (dict == null)
                return default(T2);

            T2 ret;
            dict.TryGetValue(key, out ret);
            return ret;
        }

魔术师Dix's avatar
魔术师Dix 已提交
224
        public static long Int2ToLong(Vector2Int v)
225 226 227 228 229 230 231
        {
            int q = v.x, r = v.y;
            long rt = (long)q << 32;
            rt = rt | (r & 0xffffffff);
            return rt;
        }

魔术师Dix's avatar
魔术师Dix 已提交
232
        public static Vector2Int LongToInt2(long id)
233 234 235
        {
            int x = (int)(id >> 32);
            int y = (int)id;
魔术师Dix's avatar
魔术师Dix 已提交
236
            return new Vector2Int(x, y);
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 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
        }

        /// <summary>
        /// 通过线性采样获得的颜色值;
        /// </summary>
        public static Color GetBilinearPixel(NativeArray<Color32> pixelData, float u, float v, int width, int height)
        {
            u *= width;
            v *= height;
            width = Mathf.Max(width, 2);
            height = Mathf.Max(height, 2);
            int x = Mathf.Clamp(Mathf.FloorToInt(u), 0, width - 2);
            int y = Mathf.Clamp(Mathf.FloorToInt(v), 0, height - 2);
            float s = u - x;
            float t = v - y;
            Color c1 = pixelData[x + (y * width)];
            Color c2 = pixelData[x + 1 + (y * width)];
            Color c3 = pixelData[x + ((y + 1) * width)];
            Color c4 = pixelData[x + 1 + ((y + 1) * width)];
            Color a = Color.Lerp(c1, c2, s);
            Color b = Color.Lerp(c3, c4, s);
            return Color.Lerp(a, b, t);
        }

        #endregion

        #region 数学计算

        /// <summary>
        /// 计算直线与平面的交点
        /// 
        /// 通用的部分;
        /// 
        /// ——程一峰;2020.11.09
        /// </summary>
        /// <param name="point">直线上某一点</param>
        /// <param name="direct">直线的方向</param>
        /// <param name="planeNormal">垂直于平面的的向量</param>
        /// <param name="planePoint">平面上的任意一点</param>
        /// <returns></returns>
        public static Vector3 GetIntersectWithLineAndPlane(Vector3 point, Vector3 direct, Vector3 planeNormal, Vector3 planePoint)
        {
            float d = Vector3.Dot(planePoint - point, planeNormal) / Vector3.Dot(direct.normalized, planeNormal);
            //直线与平面的交点
            Vector3 hitPoint = (d * direct.normalized) + point;
            return hitPoint;
        }

        /// <summary>
        /// 点到直线的距离;
        /// </summary>
        /// <param name="point">目标点</param>
        /// <param name="linePoint1">直线上一点</param>
        /// <param name="linePoint2">直线上另一点</param>
        /// <returns></returns>
        public static float GetDistancePointToLine(Vector3 point, Vector3 linePoint1, Vector3 linePoint2)
        {
            Vector3 vec1 = point - linePoint1;
            Vector3 vec2 = linePoint2 - linePoint1;
            Vector3 vecProj = Vector3.Project(vec1, vec2);
            float dis = Mathf.Sqrt(Mathf.Pow(Vector3.Magnitude(vec1), 2) - Mathf.Pow(Vector3.Magnitude(vecProj), 2));
            return dis;
        }

        /// <summary>
        /// 
        /// 计算射线与平面的交点
        /// 
        /// 通用的部分;
        /// 
        /// ——程一峰;2020.11.17
        /// </summary>
        /// <param name="ray">射线</param>
        /// <param name="planeNormal">垂直于平面的的向量</param>
        /// <param name="planePoint">平面上的任意一点</param>
        /// <returns></returns>
        public static Vector3 GetIntersectWithLineAndPlane(Ray ray, Vector3 planeNormal, Vector3 planePoint) { return GetIntersectWithLineAndPlane(ray.origin, ray.direction, planeNormal, planePoint); }

        /// <summary>
        /// 
        /// 计算射线与水平平面的交点
        /// 
        /// 通用的部分;
        /// 
        /// ——程一峰;2020.11.17
        /// </summary>
        /// <param name="ray">射线</param>
        /// <param name="height">高度</param>
        /// <returns></returns>
        public static Vector3 GetIntersectWithLineAndPlane(Ray ray, float height)
        {
            var point = GetIntersectWithLineAndPlane(ray.origin, ray.direction, Vector3.up, new Vector3(0, height, 0));
            point.y = height;
            return point;
        }

        /// <summary>
        /// 将值限制在两个Vector3之间
        /// </summary>
        /// <param name="pos"></param>
        /// <param name="min"></param>
        /// <param name="max"></param>
        /// <returns></returns>
        public static Vector3 Clamp(Vector3 pos, Vector3 min, Vector3 max)
        {
            pos.x = Mathf.Clamp(pos.x, min.x, max.x);
            pos.y = Mathf.Clamp(pos.y, min.y, max.y);
            pos.z = Mathf.Clamp(pos.z, min.z, max.z);
            return pos;
        }

        public static Vector2 Clamp(this Vector2 source, Vector2 min, Vector2 max)
        {
            source.x = Mathf.Clamp(source.x, min.x, max.x);
            source.y = Mathf.Clamp(source.y, min.y, max.y);
            return source;
        }

        /// <summary>
        /// 距离的平方;
        /// </summary>
        public static float DistanceSq(Vector3 a, Vector3 b)
        {
            float xSq = (a.x - b.x) * (a.x - b.x);
            float ySq = (a.y - b.y) * (a.y - b.y);
            float zSq = (a.z - b.z) * (a.z - b.z);
            return xSq + ySq + zSq;
        }

        /// <summary>
        /// 距离的平方;
        /// </summary>
        public static float DistanceSq(Vector2 a, Vector2 b)
        {
            float xSq = (a.x - b.x) * (a.x - b.x);
            float ySq = (a.y - b.y) * (a.y - b.y);
            return xSq + ySq;
        }

        /// <summary>
        /// 获取坐标差值之和;
        /// 忽略Y轴;
        /// 这个计算值一定大于等于其实际距离;
        /// </summary>
        public static float Distance_FastByCoDiff_NoY(Vector3 v1, Vector3 v2)
        {
            float x = v1.x - v2.x;
            if (x < 0)
                x = -x;

            float z = v1.z - v2.z;
            if (z < 0)
                z = -z;

            return x + z;
        }

        #endregion

        #region 字符串操作

        /// <summary>
        /// 把字符串用 . 分开;
        /// 然后获取最后一个字符串;
        /// </summary>
        /// <param name="oldStr"></param>
        /// <returns></returns>
        public static string GetLastStrAfterDot(string oldStr)
        {
            var arrStr = oldStr.Split('.');
            return arrStr[arrStr.Length - 1];
        }

        #endregion

    }
}