unity将组件值粘贴到派生组件中

在重构项目中,由于秉持着不更改框架的原则下,经常会遇到一个组件需要替换成派生的子类组件,比如将下面的组件进行替换,当两者的变量值一样时还好说,然而大多数情况时是不一样的

一种方法是进入调试面板,直接将脚本替换成派生类型

另一种方法是编写脚本

public static class ComponentTool
{
    
    
    private static SerializedObject source;
    [MenuItem("CONTEXT/Component/CopySerialized")]
    public static void Copy(MenuCommand command)
    {
    
    
        source = new SerializedObject(command.context);
    }
    [MenuItem("CONTEXT/Component/PasteSerialized")]
    public static void Paste(MenuCommand command)
    {
    
    
        SerializedObject component = new SerializedObject(command.context);
        SerializedProperty iterator = source.GetIterator();
        if (iterator.NextVisible(true))
        {
    
    
            while (iterator.NextVisible(true))
            {
    
    
                SerializedProperty property = component.FindProperty(iterator.name); 
                if (property != null && property.propertyType == iterator.propertyType) 
                {
    
    
                    component.CopyFromSerializedProperty(iterator); 
                }
            }
        }
        component.ApplyModifiedProperties();
    }
}

便可以在组件的右键菜单中快速复制粘贴

猜你喜欢

转载自blog.csdn.net/qq_25969985/article/details/126971958