前言:
在使用Unity的Transform函数时,我们会发现其自身提供的API有时候并不能完全满足我们的需求。因此我们可能会写一些方法去实现我们的需求。但是有时候这个需求在多个不同的类中都需要。这时候我们就要使用一个帮助类去减少我们重复的工作。不过人都是懒惰的,我不希望多声明一个类然后再去使用。那么我们可以使用C#的扩展类方法让Transform直接可以调用我们写的方法。具体实现如下。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| using System.Collections; using System.Collections.Generic; using UnityEngine;
public static class TransformHelper { public static Transform FindByNameDFS(this Transform transform, string target) { Transform res = null; for (int i = 0; i < transform.childCount; ++i) { Transform tmp = transform.GetChild(i); if (tmp.name == target) { res = tmp; } else { res = tmp.FindByNameDFS(target); } if (res != null) { break; } } return res; } public static Transform FindByNameBFS(this Transform transform, string target) { Transform res = null; Queue<Transform> q = new Queue<Transform>(); q.Enqueue(transform); while (q.Count != 0) { Transform head = q.Dequeue(); for (int i = 0; i < head.childCount; ++i) { Transform child = head.GetChild(i); if (child.name == target) { res = child; q.Clear(); break; } q.Enqueue(child); } } return res; } }
|