最近在项目中需要开发一套地图数据生成编辑器,记录自己在这个过程中使用的一些好用的创建和替换Prefab的方法。
PrefabUtility.CreatePrefab(localPath,obj) 这个方法可以将场景中的GameObject对象创建成Prefab,官方文档中有给出例子:
using UnityEngine;using UnityEditor;public class Example : EditorWindow{//Creates a new menu (Examples) with a menu item (Create Prefab)[MenuItem("Examples/Create Prefab")]static void CreatePrefab(){//Keep track of the currently selected GameObject(s)GameObject[] objectArray = Selection.gameObjects;//Loop through every GameObject in the array aboveforeach (GameObject gameObject in objectArray){//Set the path as within the Assets folder, and name it as the GameObject's name with the .prefab formatstring localPath = "Assets/" + gameObject.name + ".prefab";//Check if the Prefab and/or name already exists at the pathif (AssetDatabase.LoadAssetAtPath(localPath, typeof(GameObject))){//Create dialog to ask if User is sure they want to overwrite existing Prefabif (EditorUtility.DisplayDialog("Are you sure?","The Prefab already exists. Do you want to overwrite it?","Yes","No"))//If the user presses the yes button, create the Prefab{CreateNew(gameObject, localPath);}}//If the name doesn't exist, create the new Prefabelse{Debug.Log(gameObject.name + " is not a Prefab, will convert");CreateNew(gameObject, localPath);}}}// Disable the menu item if no selection is in place[MenuItem("Examples/Create Prefab", true)]static bool ValidateCreatePrefab(){return Selection.activeGameObject != null;}static void CreateNew(GameObject obj, string localPath){//Create a new Prefab at the path givenObject prefab = PrefabUtility.CreatePrefab(localPath, obj);PrefabUtility.ReplacePrefab(obj, prefab, ReplacePrefabOptions.ConnectToPrefab);}}
PrefabUtility.InstantiatePrefab(obj) 这个方法是可以克隆出一个Prefab到场景中。
string assetPath = "Assets/Prefabs/test.prefab";var prefab = AssetDatabase.LoadAssetAtPath <GameObject>(assetPath);GameObject clone = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
如果是场景中的Prefab预制对象的引用丢失,可以使用这个方法来克隆出对象,引用同样可用。