需求分析
对于A的各组件,找B中寻找对应组件
- 若有,则将本组件对应值复制给B的对应组件
- 若无,则为B添加该组件,复制A中该组件的值给B中新添加的组件
所需功能拆解
获取A的所有组件
Component[] aComponents= 游戏对象A.GetComponents<Component>();
- 获取A上挂接的所有组件,不包括其子孙节点上的组件
判断B中是否存在目标组件
B上的所有组件分别是bComponents(获取方法同上)
当前要判断是否能在B的组件中找到与A上的组件a一样(类型相同)的组件,设找到的组件是targetComponent
- Component targetComponent = bComponents.Find((item) => item.GetType() == a.GetType());
若targetComponent !=null,则表示在b的所有组件中找到了目标组件targetComponent
复制组件
UnityEditorInternal.ComponentUtility.CopyComponent(要复制数据信息的组件);
粘贴组件
UnityEditorInternal.ComponentUtility.PasteComponentValues(targetComponent );
新添加组件并粘贴
UnityEditorInternal.ComponentUtility.PasteComponentAsNew(要添加组件的gameObject);