-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrefabCreation.cs
80 lines (69 loc) · 3.05 KB
/
PrefabCreation.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using System.IO;
using UnityEngine;
using UnityEditor;
namespace UnitEditorPipeline
{
public static class PrefabCreation
{
[MenuItem("Assets/Create Mesh Prefab")]
public static void CreateMeshPrefabMenuItem()
{
Object[] selectedAssets = Selection.GetFiltered(typeof(Object), SelectionMode.Assets);
CreateMeshPrefab(selectedAssets[0]);
}
public static void CreateMeshPrefab(Object fbxAsset)
{
string fbxPath = AssetDatabase.GetAssetPath(fbxAsset);
Debug.Log($"Importing: {fbxPath}");
AssetDatabase.ImportAsset(fbxPath);
if (ModelData.AssetType == ModelData.AssetTypes.Mesh)
{
string prefabPath = CreatePrefab(fbxAsset);
if (ModelData.MeshProperties.Static)
{
Debug.Log($"{fbxPath} is a static mesh.");
SetStatic(prefabPath);
}
}
}
private static string CreatePrefab(Object fbxAsset)
{
string fbxPath = AssetDatabase.GetAssetPath(fbxAsset);
GameObject fbxMainAsset = (GameObject)AssetDatabase.LoadMainAssetAtPath(fbxPath);
string prefabName = $"{fbxMainAsset.name}_PFB";
GameObject prefabRootGO = new GameObject(prefabName);
string prefabPath = Path.Combine(Path.GetDirectoryName(fbxPath), prefabRootGO.name + ".prefab");
PrefabUtility.SaveAsPrefabAssetAndConnect(prefabRootGO, prefabPath, InteractionMode.AutomatedAction);
//Edit the Prefab to put the FBX inside it
using (var editingScope = new PrefabUtility.EditPrefabContentsScope(prefabPath))
{
var prefabRoot = editingScope.prefabContentsRoot;
GameObject instantiatedFbx = PrefabUtility.InstantiatePrefab(fbxMainAsset) as GameObject;
instantiatedFbx.transform.parent = prefabRoot.transform;
}
Object.DestroyImmediate(prefabRootGO);
Debug.Log("Created prefab: " + prefabPath);
return prefabPath;
}
private static void SetStatic(string prefabPath)
{
using (var editingScope = new PrefabUtility.EditPrefabContentsScope(prefabPath))
{
var flags = StaticEditorFlags.ContributeGI
| StaticEditorFlags.OccluderStatic
| StaticEditorFlags.BatchingStatic
| StaticEditorFlags.OccludeeStatic
| StaticEditorFlags.ReflectionProbeStatic;
var prefabRoot = editingScope.prefabContentsRoot;
Transform[] allChildren = prefabRoot.transform.GetComponentsInChildren<Transform>();
foreach (Transform child in allChildren)
{
if (child.GetComponent<Renderer>())
{
GameObjectUtility.SetStaticEditorFlags(child.gameObject, flags);
}
}
}
}
}
}