Unity学习笔记--如何用代码Copy Component并且Paste到其他游戏对象上?

前言

最近需要在编辑器模式下,用代码实现复制一个组件并且移动到另一个游戏对象上
简单来说就是剪切

解决办法

通过查询Unity API可以了解到 UnityEditorInternal.ComponentUtility.CopyComponent

比如我们想把A游戏对象上的Rigidbody组件移动到B游戏对象上

private void CopyRBCompToRoot(GameObject target_go, GameObject copied_go)
{
    
    
	var rb_comp = target_go.GetComponent<Rigidbody>();
	UnityEditorInternal.ComponentUtility.CopyComponent(rb_comp);//复制当前组件
	UnityEditorInternal.ComponentUtility.PasteComponentAsNew(target_go);//粘贴组件
}

进阶玩法

有时候,我们可能需要把一个游戏对象上的部分组件拷贝下来,那这个时候该怎么做呢?

我们可以首先拿到所有的组件,然后写一个过滤器,只需要拷贝我们需要的组件类型就好了

private static void CopyCompsToRoot(GameObject target_go, GameObject copy_go)
{
    
    
	//不需要copy的过滤器
    HashSet<System.Type> filter_types = new HashSet<System.Type>() {
    
     typeof(Transform), typeof(Animator) };
    
    Component[] copied_comps = copy_go.GetComponents<Component>();
    
    foreach (Component comp in copied_comps)
    {
    
    
        if (CheckCanCopyComp(comp, filter_types))
        {
    
    
            UnityEditorInternal.ComponentUtility.CopyComponent(comp);
            UnityEditorInternal.ComponentUtility.PasteComponentAsNew(target_go);
            Object.DestroyImmediate(comp);//这里由于需求,我们需要在粘贴之后删除原组件
        }
    }
}

private static bool CheckCanCopyComp(Component comp ,HashSet<System.Type> types)
{
    
    
    HashSet<System.Type> types = new HashSet<System.Type>()
    {
    
    
        typeof(PrincePrefabAssetTracker), typeof(Transform), typeof(Animator)
    };
    if (types.Contains(comp.GetType()))
    {
    
    
        return false;
    }
    return true;
}

猜你喜欢

转载自blog.csdn.net/qq_52855744/article/details/128906874