unity 扩展

public static class GameObjectHelper
{
    const string gameObjectIsNull = "GameObject is Null";
    public static T IsAddComponent<T>(this GameObject self)where T:Component
    {
        Assert.IsNotNull(self, gameObjectIsNull);
        var com = self.GetComponent<T>();
        if(com == null)
        {
            com = self.AddComponent<T>();
        }
        return com;
    }
}
public static class TransformHelper
{
    const string transformIsNull = "Transform is Null";
    public static T IsAddComponent<T>(this Transform self) where T : Component
    {
        Assert.IsNotNull(self, transformIsNull);
        return self.gameObject.IsAddComponent<T>();
    }
    public static Transform GetRoot(this Transform self)
    {
        Assert.IsNotNull(self, transformIsNull);
        Transform transform = self;
        while(transform.parent)
        {
            transform = transform.parent;
        }
        return transform;
    }
    public static Transform [] GetChilds(this Transform self)
    {
        Assert.IsNotNull(self, transformIsNull);
        List<Transform> list = new List<Transform>();
        Queue<Transform> stack = new Queue<Transform>();
        stack.Enqueue(self);
        while (stack.Count>0)
        {
            var transform = stack.Dequeue();
            for (var i=0;i<transform.childCount;i++)
            {
                var child = transform.GetChild(i);
                stack.Enqueue(child);
                list.Add(child);
            }
        }
        return list.ToArray();
    }
    public static Transform FindChildsName(this Transform self,string name)
    {
        var array = self.GetChilds();
        for(int i=0,end=array.Length;i<end;i++)
        {
            if (array[i].gameObject.name.Equals(name))
                return array[i];
        }
        return null;
    }
    public static Transform[] GetChildsTag(this Transform self,string tag)
    {
        var array = self.GetChilds();
        List<Transform> list = new List<Transform>();
        for(int i = 0,end=array.Length; i < end; i++)
        {
            if(array[i].gameObject.tag.Equals(tag))
            {
                list.Add(array[i]);
            }
        }
        return list.ToArray();
    }
    public static Transform[] GetChildsLayer(this Transform self, string layer)
    {
        return self.GetChildsLayer(LayerMask.NameToLayer(layer));
    }
    public static Transform[] GetChildsLayer(this Transform self, int layer)
    {
        var array = self.GetChilds();
        List<Transform> list = new List<Transform>();
        for (int i = 0, end = array.Length; i < end; i++)
        {
            if (array[i].gameObject.layer == layer)
            {
                list.Add(array[i]);
            }
        }
        return list.ToArray();
    }
}

你可能感兴趣的:(unity3d,C#,unity,扩展)