Last active
August 29, 2015 14:27
-
-
Save teessider/66c630add5a942945779 to your computer and use it in GitHub Desktop.
Unity API Example in C# - PrefabUtility.CreateEmptyPrefab & PrefabUtility.ReplacePrefab. You will need to put this in Assets/Editor (make it if it doesn't already exist) as this is a Editor script.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEditor; | |
public class CreatePrefabEditor | |
{ | |
/* Example from Unity API Documentation for: | |
* PrefabUtility.CreateEmptyPrefab (Looks like a duplicate example) & | |
* PrefabUtiltiy.ReplacePrefab | |
* Converted from UnityScript to C# | |
* | |
* However, if you make a prefab from the project folder, there are a few errors | |
* generated from the CreateNew() function. | |
* | |
* Creates a prefab from the selected GameObjects. | |
* If the prefab already exists it asks if you want to replace it | |
* | |
*/ | |
[MenuItem("Examples/Create Prefab From Selected")] | |
private static void CreatePrefab() | |
{ | |
GameObject[] objs = Selection.gameObjects; | |
/* For each gameobject in selected array, | |
* Creates an empty prefab then replaces it | |
*/ | |
foreach(GameObject go in objs) | |
{ | |
string localPath = "Assets/" + go.name + ".prefab"; | |
if (AssetDatabase.LoadAssetAtPath<GameObject>(localPath)) | |
{ | |
if (EditorUtility.DisplayDialog("Are you sure?", | |
"The prefab already exists. Do you want to overwrite it?", | |
"Yes", "No")) | |
{ | |
CreateNew(go, localPath); | |
} | |
} | |
else | |
{ | |
CreateNew(go, localPath); | |
} | |
} | |
} | |
[MenuItem("Examples/Create Prefab From Selected", true)] | |
bool ValidateCreatePrefab() | |
{ | |
return Selection.activeGameObject != null; | |
} | |
// Create Empty Prefab and then Replace | |
static void CreateNew(GameObject obj, string localPath) | |
{ | |
Object prefab = PrefabUtility.CreateEmptyPrefab(localPath); | |
PrefabUtility.ReplacePrefab(obj, prefab, ReplacePrefabOptions.ConnectToPrefab); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment