using UnityEngine; /// /// 组件拓展 /// public static class ComponentExtend { /// /// 获取某对象下的子物体,适用于多层级父子关系的查找 /// /// 子物体名称 /// /// public static Transform FindChildByName(this Component self, string objName) { if (self == null || string.IsNullOrEmpty(objName)) return null; Transform[] children = self.GetComponentsInChildren(true); for (int i = 0; i < children.Length; i++) { if (children[i].name.Equals(objName)) return children[i]; } return null; } /// /// 获取某物体下的子物体上的某个组件,适用于多层级父子关系的查找 /// /// 组件类型 /// /// 子物体名称 /// public static T GetComponentByChildName(this Component self, string objNmae) where T : Component { Transform tf = FindChildByName(self, objNmae); if (tf != null) return tf.GetComponent(); else return null; } /// /// 自动检查并添加组件 /// /// 组件类型 /// 添加组件的Component /// 是否删除已有并重新添加组件 /// public static T AutoComponent(this Component self, bool CoverModel = false) where T : Component { if (CoverModel) { if (self.TryGetComponent(out T destroy)) Object.Destroy(destroy); return self.gameObject.AddComponent(); } else { if (self.TryGetComponent(out T component)) return component; else return self.gameObject.AddComponent(); } } /// /// 自动检查并添加组件 /// /// 组件类型 /// 添加组件的GameObject /// 是否删除已有并重新添加组件 /// public static T AutoComponent(this GameObject self, bool CoverModel = false) where T : Component { if (CoverModel) { if (self.TryGetComponent(out T destroy)) Object.Destroy(destroy); return self.gameObject.AddComponent(); } else { if(self.TryGetComponent(out T component)) return component; else return self.gameObject.AddComponent(); } } }