用C#的this关键字,对Unity中的Transform类进行扩展的一个实例:
public static class GameHelper { public static void FindChildRecursive(this Transform node, string name, ref Transform target) { if (!node || string.IsNullOrEmpty(name)) return; if (node.name == name) target = node; else { foreach (Transform item in node) FindChildRecursive(item, name, ref target); } } public static void FindChildrenRecursive(this Transform node, string[] names, ref List<Transform> list) { if (!node || names == null) return; if (list == null) list = new List<Transform>(); int index = Array.FindIndex(names, n => n == node.name); if (index > -1) list.Add(node); foreach (Transform item in node) FindChildrenRecursive(item, names, ref list); } }
这里的扩展方法一般用来查找模型具体骨骼。