Unity有时候也需要处理大量的数据,特别是在编辑器脚本中,我们可以编写一些复杂的业务,用于预处理。
一、想做什么
1、如何在C#里面使用函数式编程?比如使用 pipeline,apply,map,filter等功能。
2、获取一个子物体的方法为GetComponentInChildren<something>(),但是如何把它转成list?
3、一个list如何调用apply/map类似的方法?
4、如何实现列表推导?给定一个list,根据它的信息和推导规则,返回一个新的list。
比如:我有一个list<GameObject>,我想返回一个list<String>,里面装载的是GameObject的名字?
5、如何用类表推导自动生成一个字典,比如:
给定【list<GameObject>】,如何生成【Dictionary<name,object>】
二、案例中的物体父子关系
列表推导:如何生成名字列表、位置列表
数据查询:如何返回符合条件的item
ForEach的使用
三、解决办法:
(1)如何把GetComponentInChildren<>()变成list
不能直接调用tolist()
把GetComponentInChildren<T>()的结果转成list:
GetComponentInChildren<Transform>().Cast<Transform>().ToList()
GetComponentInChildren<Transform>().Cast<Transform>().ToList().ForEach(x =>
{
Debug.Log(x.gameObject.name);
});
打印结果:
(2)ForEach——对所有元素执行一个方法fn,该方法没有返回值
GetComponentInChildren<Transform>().Cast<Transform>().ToList().ForEach(x => Debug.Log(x.gameObject.name));
(3)列表推导——Select:从一个list<GameObject> 生成 list<String>,显示物体的名字——Select
var res = GetComponentInChildren<Transform>().Cast<Transform>().ToList().Select(x=>x.name).ToList();
同理,可以生成Vector3类型的position
(4)filter的实现——Where
(5)list to dictionary
var d = GetComponentInChildren<Transform>().Cast<Transform>().ToList()
.ToDictionary(x => x.name, x => x);
Debug.Log($"----------{d.Count}----------");