[轉]Unity批量製做預製物體Prefab

http://www.u3dblog.com/?p=441編輯器

 

有時候場景中一大批物體都須要製做成預製物體,可是unity只能手動一個一個的建立,感受很是的蹩腳,下面一個編輯器類的方法解決你的麻煩。工具

static Object CreatePrefab(GameObject go, string name)
{
    //先建立一個空的預製物體
    //預製物體保存在工程中路徑,能夠修改("Assets/" + name + ".prefab");
    Object tempPrefab = PrefabUtility.CreateEmptyPrefab("Assets/" + name + ".prefab");
    //而後拿咱們場景中的物體替換空的預製物體
    tempPrefab = PrefabUtility.ReplacePrefab(go, tempPrefab);
    //返回建立後的預製物體
    return tempPrefab;
}

這個方法能夠隨意根據任何規則來寫,好比能夠遍歷一個物體的全部子物體,所有制做成預製物體保存到你的工程中,代碼以下:spa

[MenuItem("Tools/BatchPrefab All Children")]
public static void BatchPrefab(){
    Transform tParent = ((GameObject)Selection.activeObject).transform;
    
    Object tempPrefab;
    int i = 0;
    foreach(Transform t in tParent){
        tempPrefab = PrefabUtility.CreateEmptyPrefab("Assets/Prefab/prefab" + i + ".prefab");
        tempPrefab = PrefabUtility.ReplacePrefab(t.gameObject, tempPrefab);
        i ++;
    }
}

上面代碼中,在unity中添加了一個工具的菜單/BatchPrefab All Children(批量爲全部子物體制做預物體),首先獲取場景中選中的物體,遍歷其全部子物體,爲每個子物體制做預製物體保存在工程種的目錄下。3d

相關文章
相關標籤/搜索