关于获取所有子物件的一些描述

之前做工具时需要获取Gameobject下所有子物件,删除除了某个子物件之外其他子物件上的除了tranform的组件

关于代码片段

View Code
 1                //获取所有子物体
 2                 foreach (Transform t in go.transform)
 3                 {
 4                     if (!t.name.Equals("Quality"))
 5                     {
 6                         UnityEngine.Object.DestroyImmediate(t.renderer, true);
 7                         MeshFilter mf = t.GetComponent<MeshFilter>();
 8                         if (mf) { UnityEngine.Object.DestroyImmediate(mf, true); }
 9                     }
10                 }

那么,为什么可以直接通过foreach (Transform t in go.transform)就可以获取到所有子物件呢?

反编译unity3d的dll。可以看到Transform类  

View Code
 1 public sealed class Transform : Component, IEnumerable
 2 
 3 {
 4 
 5   ...
 6 
 7   public IEnumerator GetEnumerator()
 8      {
 9            return new Enumerator(this);
10      }
11 
12    
13 
14       //实现了接口
15        private sealed class Enumerator : IEnumerator
16         {
17             private int currentIndex = -1;
18             private Transform outer;
19 
20             internal Enumerator(Transform outer)
21             {
22                 this.outer = outer;
23             }
24 
25             public bool MoveNext()
26             {
27                 int childCount = this.outer.childCount;
28                 return (++this.currentIndex < childCount);
29             }
30 
31             public void Reset()
32             {
33                 this.currentIndex = -1;
34             }
35 
36             public object Current
37             {
38                 get
39                 {
40                     return this.outer.GetChild(this.currentIndex);
41                 }
42             }
43         }
44 }

查阅csdn.com相关资料。

在c#只要函数返回IEnumerable<T>,就能实现用foreach对元素进行遍历,代码如下

View Code
    public class ReturnIEnumerable  
    {  
    public IEnumerable<int> GetEnum() // 返回IEnumerable<T>的方法  
    {  
       for(int i=0;i<100;i++)  
       {  
        yield return i+1000; // 使用 yield return 返回  
       }  
       yield break; // 使用 yield break 退出便利  
    }  
    }  
    public static void RunSnippet()  
    {  
       ReturnIEnumerable re = new ReturnIEnumerable();  
       foreach(int i in re.GetEnum()) // 在这里调用返回了IEnumerable<T>的方法  
       {  
        System.Console.WriteLine(i);  
       }  
    }  

各种使用的场景

1.如果你返回的集合是只用于遍历,不可修改的,则返回IEnumerable<T>

2.如果返回的集合需要修改,如添加和删除元素,用ICollection<T>

3.如果返回的集合需要支持排序,索引等,用IList<T>

4.如果返回的集合要支持索引,但不能添加,删除元素,用ReadOnlyCollection<T>

原文地址:https://www.cnblogs.com/oldman/p/2600745.html