using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using UnityEngine; using UnityEngine.Networking; /// /// 基于Unity某些类的扩展 /// namespace XFramework { /// /// 扩展方法 /// public static class UnityExtentionMethod { //public static TaskAwaiter GetAwaiter(this UnityWebRequestAsyncOperation asyncOp) //{ // var // return getwa; //} //static IEnumerator ReturnSelf(TaskAwaiter awaiter ,T instruction) //{ // yield return instruction; // awaiter.OnCompleted(instruction); //} public static TaskAwaiter GetAwaiter(this AsyncOperation asyncOp) { var tcs = new TaskCompletionSource(); asyncOp.completed += obj => { tcs.SetResult(null); }; return ((Task)tcs.Task).GetAwaiter(); } /// /// 通过名称查找子对象 /// /// /// 名称 /// public static Transform FindChildTrans(this Transform trans, string childName) { Transform child = trans.Find(childName); if (child != null) return child; Transform tr; for (int i = 0; i < trans.childCount; i++) { child = trans.GetChild(i); tr = FindChildTrans(child, childName); if (tr != null) return tr; } //Debug.LogWarning($"{trans.name}里找不到名为{childName}的子对象"); return null; } public static T[] GetComponentsInRealChildren(this Transform trans, bool includeInactive = false) where T : Component { List TList = trans.GetComponentsInChildren(includeInactive).ToList(); TList.Remove(trans.GetComponent());//移除自身的 return TList.ToArray(); } /// /// 获取当前对象的某组件 /// 如获取失败则添加该组件 /// /// 组件类型 /// /// public static T GetOrAddComponent(this Transform t) where T : Component { T component = t.GetComponent(); if (component == null) component = t.gameObject.AddComponent(); return component; } /// /// 获取一个子对象的某组件 /// 如获取失败则添加 /// /// 组件类型 /// /// 子对象名称 /// public static T GetOrAddComponentInChildren(this Transform t, string childName) where T : Component { Transform childObj = t.FindChildTrans(childName); if (childObj == null) return null; return childObj.GetOrAddComponent(); } /// /// 控制一个面板的外观 /// /// /// 显示则为true /// 是否为活动对象 public static void PanelAppearance(this Transform t, bool on_off, bool active = false) { CanvasGroup group = t.GetOrAddComponent(); int value = on_off == true ? 1 : 0; //射线检测 group.blocksRaycasts = on_off; //交互 group.interactable = on_off; //透明度 group.alpha = value; t.gameObject.SetActive(on_off || active); } } }