前言
最近需要在編輯器模式下,用代碼實現(xiàn)復(fù)制一個組件并且移動到另一個游戲?qū)ο笊?br> 簡單來說就是剪切
解決辦法
通過查詢Unity API可以了解到 UnityEditorInternal.ComponentUtility.CopyComponent。
比如我們想把A游戲?qū)ο笊系?strong>Rigidbody組件移動到B游戲?qū)ο笊?/p>
private void CopyRBCompToRoot(GameObject target_go, GameObject copied_go)
{
var rb_comp = target_go.GetComponent<Rigidbody>();
UnityEditorInternal.ComponentUtility.CopyComponent(rb_comp);//復(fù)制當(dāng)前組件
UnityEditorInternal.ComponentUtility.PasteComponentAsNew(target_go);//粘貼組件
}
進階玩法
有時候,我們可能需要把一個游戲?qū)ο笊系牟糠纸M件拷貝下來,那這個時候該怎么做呢?文章來源:http://www.zghlxwxcb.cn/news/detail-605438.html
我們可以首先拿到所有的組件,然后寫一個過濾器,只需要拷貝我們需要的組件類型就好了文章來源地址http://www.zghlxwxcb.cn/news/detail-605438.html
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;
}
到了這里,關(guān)于Unity學(xué)習(xí)筆記--如何用代碼Copy Component并且Paste到其他游戲?qū)ο笊希康奈恼戮徒榻B完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!