Unity 公用函数整理【一】

1.眨眼效果

 /// <summary>
    /// 眨眼效果
    /// </summary>
    /// <param name="eyeMaskRenserer">眼遮罩</param>
    /// <param name="blinkTime">眨眼时间</param>
    /// <param name="callback">眨眼后回调</param>
    /// <returns></returns>
    public static IEnumerator IEBlinkEye(SpriteRenderer eyeMaskRenserer, float blinkTime, Action callback)
    {
        SetTrs(eyeMaskRenserer.transform, true);
        var startColor = Color.clear;
        var targetColor = Color.black;
        var startTime = Time.time;
        var needTime = 1f;
        eyeMaskRenserer.color = startColor;
        while (eyeMaskRenserer.color.a < 0.99f)
        {
            eyeMaskRenserer.color = Color.Lerp(startColor, targetColor, (Time.time - startTime) * needTime);
            yield return null;
        }
        eyeMaskRenserer.color = targetColor;

        if (blinkTime > 2f)
        {
            yield return new WaitForSeconds(blinkTime - 2f);
            callback?.Invoke();
        }



        startColor = Color.black;
        targetColor = Color.clear;
        startTime = Time.time;
        eyeMaskRenserer.color = startColor;
        while (eyeMaskRenserer.color.a > 0.01f)
        {
            eyeMaskRenserer.color = Color.Lerp(startColor, targetColor, (Time.time - startTime) * needTime);
            yield return null;
        }
        eyeMaskRenserer.color = targetColor;
        SetTrs(eyeMaskRenserer.transform, false);
    }
     /// <summary>
    /// 变化眼睛颜色
    /// </summary>
    public void ChangEyeColor2(Color startColor, Color endColor, float changeTime, Action ChangeCall = null)
    {
        eyeImg.color = startColor;
        eyeImg.DOColor(endColor, changeTime).OnComplete(() =>
        {
            if (ChangeCall != null)
            {
                ChangeCall.Invoke();
            }
        });
    }

2.计算两点的距离

/// <summary>
    /// 计算两点的距离
    /// </summary>
    /// <param name="point1"></param>
    /// <param name="point2"></param>
    /// <returns></returns>
    public static float CalculateTwoPointDistance(Vector3 point1, Vector3 point2)
    {
        //根据勾股定理(a²+b²=c²)求出支撑杆长度,开c的平方根得到弦的长度
        float c = Vector3.Distance(point2, point1);
        float a = Mathf.Abs(point2.y - point1.y);
        return Mathf.Sqrt(Mathf.Pow(c, 2) - Mathf.Pow(a, 2));
    }

3.Texture 相关函数


    #region  Texture2D
    /// <summary>
    /// 将Base64String转换成Texture
    /// </summary>
    /// <param name="base64Str"></param>
    /// <returns></returns>
    public static Texture2D Base64StringToTexture2D(string base64Str)
    {
        try
        {
            //将base64头部信息替换
            base64Str = base64Str.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "")
                .Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "");
            byte[] bytes = Convert.FromBase64String(base64Str);
            Texture2D texture = new Texture2D(784, 800);
            texture.LoadImage(bytes);
            return texture;
        }
        catch (Exception ex)
        {
            Debug.LogError("转换异常" + ex);
            return null;
        }
    }

    /// <summary>
    /// 编辑器模式下Texture转换成Texture2D
    /// </summary>
    /// <param name="texture"></param>
    /// <returns></returns>
    public static Texture2D TextureToTexture2D_Editor(Texture texture)
    {
        Texture2D texture2d = texture as Texture2D;
#if UNITY_EDITOR
        UnityEditor.TextureImporter ti = (UnityEditor.TextureImporter)UnityEditor.TextureImporter.GetAtPath(UnityEditor.AssetDatabase.GetAssetPath(texture2d));
        //图片Read/Write Enable的开关
        ti.isReadable = true;

        UnityEditor.AssetDatabase.ImportAsset(UnityEditor.AssetDatabase.GetAssetPath(texture2d));
#endif
        return texture2d;
    }

    /// <summary>
    /// 运行模式下Texture转换成Texture2D
    /// </summary>
    /// <param name="texture"></param>
    /// <returns></returns>
    public static Texture2D TextureToTexture2D(Texture texture, int width = 0, int height = 0)
    {
        if (width.Equals(0)) width = texture.width;
        if (height.Equals(0)) height = texture.height;

        Texture2D texture2D = new Texture2D(width, height, TextureFormat.RGBA32, false);
        RenderTexture currentRT = RenderTexture.active;

        RenderTexture renderTexture = RenderTexture.GetTemporary(width, height, 32);
        Graphics.Blit(texture, renderTexture);
        RenderTexture.active = renderTexture;
        texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
        texture2D.Apply();

        RenderTexture.active = currentRT;
        RenderTexture.ReleaseTemporary(renderTexture);
        return texture2D;
    }
    #endregion

4.设置物体的材质球

/// <summary>
        /// 设置物体上所有材质球[简单粗暴版]
        /// </summary>
        /// <param name="trs"></param>
        /// <param name="isActive"></param>
        public static void SetMaterials(Transform trs, Material material)
        {
            Material[] materials = trs.GetComponent<MeshRenderer>().materials;
            for (int i = 0; i < materials.Length; i++)
            {
                materials[i] = material;
            }
            trs.GetComponent<MeshRenderer>().materials = materials;
        }

        /// <summary>
        /// 设置物体上所有材质球[升级版]
        /// </summary>
        /// <param name="trs"></param>
        /// <param name="isActive"></param>
        public void SetMaterials(Transform trs, params Material[] p_mat)
        {
            Material[] materials = trs.GetComponent<MeshRenderer>().materials;
            int length = p_mat.Length > materials.Length ? p_mat.Length : materials.Length;
            Material[] mats = new Material[length];
            for (int i = 0; i < length; i++)
            {
                if (i >= p_mat.Length)
                {
                    mats[i] = materials[i];
                    continue;
                }
                mats[i] = p_mat[i];
            }
            //materials = mats;
            trs.GetComponent<MeshRenderer>().materials = mats;
        }

5.设置物体高亮

/// <summary>
    /// 物体高亮
    /// </summary>
    /// <param name="obj"></param>
    /// <param name="flag"></param>
    /// <param name="endColor"></param>
    /// <param name="startColor"></param>
    public static void HightLightController(GameObject obj, bool flag, Color endColor = new Color(), Color startColor = new Color())
    {
        if (obj != null)
        {
            FlashingController flashing = obj.gameObject.GetComponent<FlashingController>();
            if (flag)
            {
                if (!flashing)
                    flashing = obj.gameObject.AddComponent<FlashingController>();
                flashing.flashingStartColor = startColor;
                flashing.flashingEndColor = endColor;
                flashing.flashingDelay = 0f;
                flashing.flashingFrequency = 1f;
                flashing.enabled = true;
            }
            else
            {
                if (flashing)
                {
                    UnityEngine.Object.Destroy(flashing);
                    Highlighter high = obj.GetComponent<Highlighter>();
                    if (high)
                        UnityEngine.Object.Destroy(high);
                }
            }
        }
    }
  /// <summary>
  /// 设置高亮
  /// </summary>
  /// <param name="obj"></param>
  /// <param name="active"></param>
  public static void OutlineController(Transform obj, bool active)
  {
      if (active)
      {
          if (obj.GetComponent<Outline>() == null)
          {
              var controller = obj.gameObject.AddComponent<Outline>();
              controller.OutlineColor = Color.red;
              controller.OutlineWidth = 3f;
              controller.Flashfrequency = 4f;
              controller.PrecomputeOutline = true;
              controller.Needflash = true;
              controller.enabled = true;
          }
          else
          {
              obj.GetComponent<Outline>().enabled = true;
          }
      }
      else
      {
          if (obj.GetComponent<Outline>() != null)
          {
              obj.GetComponent<Outline>().enabled = false;
          }
      }
  }

6.延时方法

    /// <summary>
    /// 协程延时
    /// </summary>
    /// <param name="time"></param>
    /// <param name="action"></param>
    /// <returns></returns>
    public static IEnumerator _WaitTime(float wait,Action _func)
    {
        yield return new WaitForSeconds(wait);
        if (null != _func)
            _func();
    }
        /// <summary>
        /// 延迟一段时间执行回调
        /// </summary>
        /// <param name="delay"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public static void DelayByDOTween(float delay, Action action)
        {
            var timer = 0f;
            DOTween.To(() => timer, x => timer = x, 1f, delay).OnComplete(() => { action.Invoke(); });
        }

7.通过名称查找子物体

 /// <summary>
    /// 通过名称查找未知层级子物体
    /// </summary>
    /// <param name="parentTF"></param>
    /// <param name="childName"></param>
    /// <returns></returns>
    public static Transform GetChild(Transform parentTF, string childName)
    {
        //在子物体中查找名为childName 的子物体,如果有就返回,如果没有就开始递归
        Transform childTF = parentTF.Find(childName);
        if (childTF != null) return childTF;
        //将问题交由子物体
        int count = parentTF.childCount;
        for (int i = 0; i < count; i++)
        {
            childTF = GetChild(parentTF.GetChild(i), childName);
            if (childTF != null)
            {
                return childTF;
            }
        }
        return null;
    }

8.动态创建Tag

/// <summary>
    /// 检查tag列表中是否有tag,没有该tag添加此tag
    /// </summary>
    /// <param name="tag">所要设设置的tag</param>
    public static void SetGameObjectTag(GameObject gameObject, string tag)
    {
#if UNITY_EDITOR
        if (!UnityEditorInternal.InternalEditorUtility.tags.Equals(tag)) //如果tag列表中没有这个tag
        {
            UnityEditorInternal.InternalEditorUtility.AddTag(tag); //在tag列表中添加这个tag
        }
#endif
        gameObject.tag = tag;
    }

9.对子物体进行排序


    private void Sort(Transform root)
    {
        foreach (Transform item in GetTransforms(root))
        {
            item.SetAsLastSibling();//从小到大排序
            //item.SetAsFirstSibling();//从大到小排序
        }
    }

    /// <summary>
    /// 返回 children transforms, 根据名称排列 .
    /// </summary>
    public Transform[] GetTransforms(Transform parentGameObject)
    {
        if (parentGameObject != null)
        {
            List<Component> components = new List<Component>(parentGameObject.GetComponentsInChildren(typeof(Transform)));
            List<Transform> transforms = components.ConvertAll(c => (Transform)c);

            transforms.Remove(parentGameObject.transform);
            transforms.Sort(delegate (Transform a, Transform b)
            {
                return a.name.CompareTo(b.name);
            });

            return transforms.ToArray();
        }

        return null;
    }

10.设置材质球的自发光_EMISSION属性

 /// <summary>
 /// 设置材质球的自发光_EMISSION属性
 /// </summary>
 /// <param name="trs"></param>
 /// <param name="isActive"></param>
 public static void SetMaterialsEmission(Transform trs, bool isActive)
 {
     Renderer[] rds = trs.GetComponentsInChildren<Renderer>();
     //逐一遍历他的子物体中的Renderer
     foreach (Renderer render in rds)
     {
         Material[] materials = render.GetComponent<MeshRenderer>().materials;
         for (int i = 0; i < materials.Length; i++)
         {
             if (isActive)
                 materials[i].EnableKeyword("_EMISSION");
             else
                 materials[i].DisableKeyword("_EMISSION");
         }
     }
 }

猜你喜欢

转载自blog.csdn.net/U3DCoder/article/details/126510629