source:被替换的组件脚本,target:要替换的目标脚本。
前言
在游戏开发过程中,组件A已经大范围使用,后续因为需求原因导致我们需要对组件A进行拓展,并且不影响原来的功能的情况下,替换成扩展后的组件B,此时需要替换的范围是整个游戏内已经制作完成的prefab,上百个都是有可能的。
假设我们还使用了prefab的嵌套和变体的情况下,如果单纯的使用DestroyObjectImmediate和AddComponent,嵌套和变体就会引发新的问题。
本篇就是实现:丝滑替换组件并且保留原有的序列化信息
思路:通过修改序列化信息的m_Script来实现组件替换
方法一:手动修改
方法二:项目组一般替换会涉及全部替换,手动替换不现实,直接通过代码修改prefab的序列化信息达到替换的效果
source:被替换的组件脚本,target:要替换的目标脚本。
//assetPath:该prefab在Assets下的路径
GameObject root = AssetDatabase.LoadAssetAtPath<GameObject>(assetPath);
//scriptPath:targe的脚本在Assets下的路径
var scriptPath = "Assets/Test/UITargete