public static void GeneratePlayerData() { var excelPath = Application.dataPath + facadeExcelPath; var facadeSet = ReadExcel(excelPath); var facadeTables = facadeSet.Tables; foreach (var table in facadeTables) { var rows = table.Rows; if (rows == null) { continue; } if (rows.Count < 3) { continue; } if (rows[0].Cells.Count < 6) { continue; } if (!rows[0].Cells[facadeModelNum].Equals(ModelStr) || !rows[0].Cells[facadeTextureNum].Equals(TextureStr)) { continue; } for (int i = 0; i < rows.Count; ++i) { if (i == 0) { continue; } var row = rows[i]; var kv = row.Cells[facadeTextureNum].Trim(); if (kv == string.Empty) { continue; } if (!texturesDic.ContainsKey(kv)) { texturesDic.Add(kv, kv); } continue; var modelsStr = row.Cells[facadeModelNum].Trim(); if (modelsStr == string.Empty) { continue; } var __modelsStr = modelsStr.Split(';'); List <string> modelStrList = new List <string>(); foreach (var _modelsStr in __modelsStr) { var es = _modelsStr.Split('|'); for (int j = 0; j < es.Length; j++) { if (es[j].Trim() != string.Empty) { modelStrList.Add(es[j].Trim()); } } } foreach (var k in modelStrList) { if (!modelsDic.ContainsKey(k)) { modelsDic.Add(k, k); } } } } excelPath = Application.dataPath + equipExcelPath; var equipSet = ReadExcel(excelPath); var equipTables = equipSet.Tables; foreach (var table in equipTables) { var rows = table.Rows; if (rows == null) { continue; } if (rows.Count < 3) { continue; } if (rows[0].Cells.Count < 6) { continue; } if (!rows[0].Cells[equipModelNum].Equals(ModelStr) || !rows[0].Cells[equipTextureNum].Equals(TextureStr)) { continue; } for (int i = 0; i < rows.Count; ++i) { if (i == 0) { continue; } var row = rows[i]; var kv = row.Cells[equipTextureNum].Trim(); if (kv == string.Empty) { continue; } if (!texturesDic.ContainsKey(kv)) { texturesDic.Add(kv, kv); } continue; var modelsStr = row.Cells[equipModelNum].Trim(); if (modelsStr == string.Empty) { continue; } var __modelsStr = modelsStr.Split(new [] { ';', '|' }); foreach (var k in __modelsStr) { if (!modelsDic.ContainsKey(k)) { modelsDic.Add(k, k); } } } } sourceTexPathDic.Clear(); GetAllAssetPath(sourceTexPathDic, sourcePath, "t:Texture"); targetTexPathDic.Clear(); GetAllAssetPath(targetTexPathDic, targetPath, "t:Texture"); foreach (var tex in texturesDic) { if (!targetTexPathDic.ContainsKey(tex.Key)) { if (!sourceTexPathDic.ContainsKey(tex.Key)) { DebugLogWrapper.LogError("asset miss>>>" + tex.Key); continue; } var sp = sourceTexPathDic[tex.Key]; var tp = targetTexturePath + GetTextureSubPath(sp); AssetDatabase.CopyAsset(sp, tp); targetTexPathDic.Add(tex.Key, tp); } } var player = AssetDatabase.LoadAssetAtPath <GameObject>(playerPath); var dummyCount = player.transform.childCount; List <GameObject> gos = new List <GameObject>(); for (int i = 0; i < dummyCount; ++i) { var child = player.transform.GetChild(i); if (child.name == "Bip01") { continue; } if (child.name == "Dummy_idle_ball") { continue; } if (child.name.Contains("Dummy_")) { var modelsCount = child.childCount; for (int j = 0; j < modelsCount; ++j) { gos.Add(child.GetChild(j).gameObject); } } } // 导出models 并且生成bones info ExportBonesInfo(gos, outPath); targetMatPathDic.Clear(); sourceMatPathDic.Clear(); // 搜集所有assert GetAllAssetPath(targetMatPathDic, targetPath, "t:Material"); GetAllAssetPath(sourceMatPathDic, sourcePath, "t:Material"); Dictionary <string, string> goPathsDic = new Dictionary <string, string>(); GetAllAssetPath(goPathsDic, targetModelsPath, "t:Prefab"); foreach (var goPath in goPathsDic) { var go = AssetDatabase.LoadAssetAtPath <GameObject>(goPath.Value); var render = go.GetComponent <Renderer>(); var mat = render.sharedMaterial; if (mat == null) { DebugLogWrapper.LogError("材质丢失,请手动指定" + go.name); continue; } string matPath = string.Empty; if (targetMatPathDic.TryGetValue(mat.name, out matPath)) { var newMat = AssetDatabase.LoadAssetAtPath <Material>(matPath); var sourceMat = AssetDatabase.LoadAssetAtPath <Material>(sourceMatPathDic[mat.name]); // 重新指定引用的材质 render.sharedMaterial = newMat; ReplaceMatTexs(sourceMat, newMat); } else { var sourceMat = AssetDatabase.LoadAssetAtPath <Material>(sourceMatPathDic[mat.name]); var newMat = new Material(sourceMat); newMat.name = sourceMat.name; AssetDatabase.CreateAsset(newMat, newMaterialsPath + newMat.name); render.sharedMaterial = newMat; ReplaceMatTexs(sourceMat, newMat); } } AssetDatabase.SaveAssets(); }
public void Generate(System.Action <Texture2D> onSave) { var pathTP = AssetDatabase.GetAssetPath(this); var filenameTP = System.IO.Path.GetFileName(pathTP); var folderTP = pathTP.Substring(0, pathTP.Length - filenameTP.Length - 1); var pathST = AssetDatabase.GetAssetPath(sourceTexture); var extensionST = System.IO.Path.GetExtension(pathST); var filenameST = System.IO.Path.GetFileName(pathST); var filenameExtensionlessST = System.IO.Path.GetFileNameWithoutExtension(pathST); var pathResult = folderTP + "/GeneratedTextures/" + filenameExtensionlessST + " (Processed by " + name + ")" + extensionST; var size = TextureProcessor.GetResultSize(this); Texture2D resTex = null; void CreateResTex() { resTex = new Texture2D(size.x, size.y, TextureFormat.ARGB32, true, false); resTex.name = filenameExtensionlessST + " (Processed by " + name + ")"; resTex.alphaIsTransparency = sourceTexture.alphaIsTransparency; resTex.filterMode = sourceTexture.filterMode; resTex.anisoLevel = sourceTexture.anisoLevel; resTex.wrapMode = sourceTexture.wrapMode; } if (result == null || (AssetDatabase.IsSubAsset(result) == saveAsExtraFile)) { DeleteResultPlusAsset(); CreateResTex(); if (saveAsExtraFile) { if (!AssetDatabase.IsValidFolder(folderTP + "/GeneratedTextures")) { AssetDatabase.CreateFolder(folderTP, "GeneratedTextures"); } if (!AssetDatabase.CopyAsset(pathST, pathResult)) { Debug.LogError("could not copy file"); return; } AssetDatabase.SaveAssets(); } else { AssetDatabase.AddObjectToAsset(resTex, this); var newFile = "___TEMP___.asset"; // TODO hack AssetDatabase.RenameAsset(pathTP, newFile); // TODO hack AssetDatabase.SaveAssets(); // TODO hack AssetDatabase.RenameAsset(pathTP.Substring(0, pathTP.Length - filenameTP.Length) + newFile, filenameTP); // TODO hack result = resTex; } } else { if (saveAsExtraFile) { CreateResTex(); // have to create anew, in case original is compressed pathResult = AssetDatabase.GetAssetPath(result); AssetDatabase.RenameAsset(pathResult, filenameExtensionlessST + " (Processed by " + name + ")" + extensionST); } else { resTex = result; if (resTex.width != size.x || resTex.height != size.y) { resTex.Resize(size.x, size.y); } } } Generate(this, resTex); if (saveAsExtraFile) { var fullPathResult = Application.dataPath + "/../" + pathResult; switch (extensionST) { case ".tga": System.IO.File.WriteAllBytes(fullPathResult, resTex.EncodeToTGA()); break; case ".jpg": case ".jpeg": System.IO.File.WriteAllBytes(fullPathResult, resTex.EncodeToJPG(90)); break; case ".exr": System.IO.File.WriteAllBytes(fullPathResult, resTex.EncodeToEXR()); break; default: System.IO.File.WriteAllBytes(fullPathResult, resTex.EncodeToPNG()); break; } AssetDatabase.ImportAsset(pathResult, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ImportRecursive | ImportAssetOptions.ForceUncompressedImport); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); result = AssetDatabase.LoadAssetAtPath <Texture2D>(pathResult); } else { AssetDatabase.ImportAsset(pathTP, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ImportRecursive | ImportAssetOptions.ForceUncompressedImport); } if (result != null) { if (onSave != null) { onSave(result); } EditorUtility.SetDirty(result); } EditorUtility.SetDirty(this); }
public static void CreateTransition(FlowWindow flowWindow, FlowWindow toWindow, string localPath, System.Action <TransitionInputTemplateParameters> callback = null) { if (flowWindow.GetScreen() == null) { return; } var screenPath = AssetDatabase.GetAssetPath(flowWindow.GetScreen()); screenPath = System.IO.Path.GetDirectoryName(screenPath); var splitted = screenPath.Split(new string[] { "/" }, System.StringSplitOptions.RemoveEmptyEntries); var packagePath = string.Join("/", splitted, 0, splitted.Length - 1); var path = packagePath + localPath; FlowChooserFilterWindow.Show <TransitionInputTemplateParameters>( root: null, onSelect: (element) => { // Clean up previous transitions if exists var attachItem = flowWindow.GetAttachItem(toWindow); if (attachItem != null) { if (attachItem.transition != null && attachItem.transitionParameters != null) { AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(attachItem.transitionParameters.gameObject)); attachItem.transition = null; attachItem.transitionParameters = null; } } if (System.IO.Directory.Exists(path) == false) { System.IO.Directory.CreateDirectory(path); } if (element == null) { return; } var elementPath = AssetDatabase.GetAssetPath(element.gameObject); var targetName = "Transition-" + element.gameObject.name + "-" + (toWindow.IsFunction() == true ? FlowSystem.GetWindow(toWindow.functionId).directory : toWindow.directory); var targetPath = path + "/" + targetName + ".prefab"; if (AssetDatabase.CopyAsset(elementPath, targetPath) == true) { AssetDatabase.ImportAsset(targetPath); var newInstance = AssetDatabase.LoadAssetAtPath <GameObject>(targetPath); var instance = newInstance.GetComponent <TransitionInputTemplateParameters>(); instance.useAsTemplate = false; EditorUtility.SetDirty(instance); attachItem.transition = instance.transition; attachItem.transitionParameters = instance; if (callback != null) { callback(instance); } } }, onEveryGUI: (element) => { // on gui var style = new GUIStyle(GUI.skin.label); style.wordWrap = true; if (element != null) { GUILayout.Label(element.name, style); } else { GUILayout.Label("None", style); } }, predicate: (element) => { var elementPath = AssetDatabase.GetAssetPath(element.gameObject); var isInPackage = FlowProjectWindowObject.IsValidPackage(elementPath + "/../"); if (element.transition != null && (isInPackage == true || element.useAsTemplate == true)) { var name = element.GetType().FullName; var baseName = name.Substring(0, name.IndexOf("Parameters")); var type = System.Type.GetType(baseName + ", " + element.GetType().Assembly.FullName, throwOnError: true, ignoreCase: true); if (type != null) { var attribute = type.GetCustomAttributes(inherit: true).OfType <TransitionCameraAttribute>().FirstOrDefault(); if (attribute != null) { return(true); } else { Debug.Log("No Attribute: " + baseName, element); } } else { Debug.Log("No type: " + baseName); } } return(false); }, strongType: false, directory: null, useCache: false, drawNoneOption: true, updateRedraw: true); }
public static void RandomizeTree(Tree template, int treeCount, bool cloneMaterials) { if (template == null) { return; } Debug.Log("Starting generation of " + treeCount + " trees."); template = GetAssetTree(template); if (!AssetDatabase.Contains(template)) { Debug.LogError("The tree was not found in the AssetDatabase.", template); return; } string path = AssetDatabase.GetAssetPath(template); string dir = Path.GetDirectoryName(path); string name = Path.GetFileNameWithoutExtension(path); string ext = Path.GetExtension(path); string outputFolder = Path.Combine(dir, Constants.OUTPUT_FOLDER); if (!AssetDatabase.IsValidFolder(outputFolder)) { AssetDatabase.CreateFolder(dir, Constants.OUTPUT_FOLDER); } var templateSerialized = new SerializedObject(template.data); Material[] materials = template.GetComponent <MeshRenderer>().sharedMaterials; Material barkmat = templateSerialized.FindProperty("optimizedSolidMaterial").objectReferenceValue as Material; if (barkmat == null) { Debug.LogError("bark material not found!"); return; } Material leafmat = templateSerialized.FindProperty("optimizedCutoutMaterial").objectReferenceValue as Material; if (leafmat == null) { Debug.LogError("leaf material not found"); return; } List <Tree> generatedTrees = new List <Tree>(); for (int i = 0; i < treeCount; i++) { string outFile = name + "_" + i + ext; string outPath = Path.Combine(outputFolder, outFile); bool success = AssetDatabase.CopyAsset(path, outPath); AssetDatabase.Refresh(); if (!success) { Debug.LogError("Could not copy the tree from " + path + " to " + outPath); return; } AssetDatabase.ImportAsset(outPath); Tree newTree = AssetDatabase.LoadAssetAtPath(outPath, typeof(Tree)) as Tree; SerializedObject newTreeSerialized = new SerializedObject(newTree.data); Material newTreeBark = newTreeSerialized.FindProperty("optimizedSolidMaterial").objectReferenceValue as Material; Material newTreeLeaf = newTreeSerialized.FindProperty("optimizedCutoutMaterial").objectReferenceValue as Material; if (!cloneMaterials) { if (newTreeBark != null) { Object.DestroyImmediate(newTreeBark, true); } if (newTreeLeaf != null) { Object.DestroyImmediate(newTreeLeaf, true); } newTreeSerialized.FindProperty("optimizedSolidMaterial").objectReferenceValue = barkmat; newTreeSerialized.FindProperty("optimizedCutoutMaterial").objectReferenceValue = leafmat; newTree.GetComponent <MeshRenderer>().sharedMaterials = materials; AssetDatabase.DeleteAsset(outputFolder + "/" + name + "_" + i + "_Textures"); } AssetDatabase.SaveAssets(); int randomSeed = Random.Range(0, 9999999); newTreeSerialized.FindProperty("root.seed").intValue = randomSeed; newTreeSerialized.ApplyModifiedProperties(); MethodInfo meth = newTree.data.GetType().GetMethod("UpdateMesh", new[] { typeof(Matrix4x4), typeof(Material[]).MakeByRefType() }); object[] arguments = new object[] { newTree.transform.worldToLocalMatrix, null }; meth.Invoke(newTree.data, arguments); generatedTrees.Add(newTree); } }
public static void SaveToAsset(Graph graph, Object targetMainAsset) { if (Application.isPlaying) { return; } string copyPath; //if (CheckAssetRef(targetMainAsset, graph.GetAllNestedGraphs<Graph>(true))) //{ // EditorUtility.DisplayDialog("无法创建资源", "无法覆盖已经被引用的资源", "OK"); // return; //} //DeleteAllUselessBoundAsset(graph); if (graph.agent != null) { Debug.Log("Save To Asset:" + graph.agent); List <Graph> allNestGraphs = new List <Graph>(); allNestGraphs.AddRange(graph.GetAllNestedGraphs <Graph>(true)); var prefabType = UnityEditor.PrefabUtility.GetPrefabType(graph.agent.gameObject); //Debug.Log("prefabType:" + prefabType); if (prefabType == UnityEditor.PrefabType.PrefabInstance || prefabType == UnityEditor.PrefabType.Prefab) { string targetMainAssetPath = AssetDatabase.GetAssetPath(targetMainAsset); string prefbPath; if (prefabType == UnityEditor.PrefabType.PrefabInstance) { //AssetDatabase.DeleteAsset(targetMainAssetPath); Object prefab = PrefabUtility.GetCorrespondingObjectFromSource(graph.agent.gameObject); // Debug.Log("Instance prefab name:" + prefab.name); prefbPath = AssetDatabase.GetAssetPath(prefab); copyPath = targetMainAssetPath; //Debug.Log("Instance prefab path:" + prefbPath); //Debug.Log("currentPrefab is not MainAsset, try to create new "); Object[] _assets = AssetDatabase.LoadAllAssetsAtPath(prefbPath); //Object MainPrefabAsset = targetMainAsset; //foreach (var asset in _assets) //{ // if (AssetDatabase.IsMainAsset(asset)) // { // Debug.Log("获得主Prefab资源物体:" + asset.name); // MainPrefabAsset = asset; // break; // } //} List <Object> assetList = _assets.ToList(); bool temp = false; foreach (var nestGraph in allNestGraphs) { if (!assetList.Contains(nestGraph)) { //Debug.Log("当前子PrefabInstance,在prefab下没有graph资源,生成它"); if (AssetDatabase.IsMainAsset(nestGraph) || AssetDatabase.IsSubAsset(nestGraph)) { //Debug.Log("当前资源已经保存到磁盘"); var newGraph = ScriptableObject.CreateInstance(nestGraph.GetType()); (newGraph as UnityEngine.Object).name = nestGraph.name; EditorUtility.CopySerialized(nestGraph, newGraph); ((Graph)newGraph).Validate(); AssetDatabase.AddObjectToAsset(newGraph, targetMainAsset); Debug.Log(string.Format("请手动调整嵌套资源: {0} 的引用", newGraph.name)); temp = true; } else { AssetDatabase.AddObjectToAsset(nestGraph, targetMainAsset); } } else { temp = true; Debug.Log(string.Format("请手动调整嵌套资源: {0} 的引用", nestGraph.name)); } } if (temp) { //Debug.Log(string.Format("手动调整恢复嵌套资源的引用后,建议使用clearUselessNestedAsset按钮,清理一次无用嵌套资源")); } UnityEditor.EditorApplication.delayCall += () => { AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(targetMainAsset)); }; //Debug.Log("prefab path:" + copyPath); //AssetDatabase.CopyAsset(prefbPath, copyPath); } else { prefbPath = AssetDatabase.GetAssetPath(graph); //Debug.Log("Realprefab path:" + prefbPath); copyPath = targetMainAssetPath; //Debug.Log("prefab path:" + copyPath); AssetDatabase.CopyAsset(prefbPath, copyPath); Object[] assets = AssetDatabase.LoadAllAssetsAtPath(copyPath); if (assets == null || assets.Length == 0) { //Debug.Log("no duplicate"); return; } Object MainAsset = assets[0]; //List<Graph> newCopyNestGraphList = new List<Graph>(); int length = assets.Length; for (int i = 0; i < length; i++) { Object asset = assets[i]; if (AssetDatabase.IsMainAsset(asset)) { MainAsset = asset; //Debug.Log(MainAsset.name); continue; } if (asset is GameObject || asset is Component) { if (asset is Transform) { continue; } Object.DestroyImmediate(asset, true); continue; } //Debug.Log("asset name:" + asset.name + " graph name:" + graph.name); if (asset.name == graph.name) { // Debug.Log("Main Scirpt:"+asset.name); ((Graph)asset).Validate(); //newCopyNestGraphList = ((Graph) asset).GetAllNestedGraphs<Graph>(true); AssetDatabase.SetMainObject(asset, copyPath); } } UnityEditor.EditorApplication.delayCall += () => { AssetDatabase.ImportAsset(copyPath); }; Object.DestroyImmediate(MainAsset, true); } UnityEditor.EditorApplication.delayCall += () => { AssetDatabase.ImportAsset(copyPath); }; AssetDatabase.Refresh(); } else //prefab parent物体模式 或者资源模式 { foreach (var v in allNestGraphs) { if (v != graph && !SaveToAssetCheckHasThisAsset(v, graph)) { if (AssetDatabase.IsMainAsset(v) || AssetDatabase.IsSubAsset(v)) { //Debug.Log("当前资源已经保存到磁盘"); var newGraph = ScriptableObject.CreateInstance(v.GetType()); (newGraph as UnityEngine.Object).name = v.name; EditorUtility.CopySerialized(v, newGraph); ((Graph)newGraph).Validate(); AssetDatabase.AddObjectToAsset(newGraph, targetMainAsset); } else { //Debug.Log("prefabNone add to mainAsset:" + v.name); AssetDatabase.AddObjectToAsset(v, targetMainAsset); ((Graph)v).Validate(); } } } UnityEditor.EditorApplication.delayCall += () => { AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(targetMainAsset)); }; AssetDatabase.Refresh(); EditorUtility.SetDirty(targetMainAsset); } } }
void MakeMaterialUnique(GameObject inputObject) { Material newMat = null; int matNumber = 0; bool inputMaterialExists = true; string newMatName = ""; if (inputObject.GetComponent <Renderer>() != null) { //Get the object material. Material sharedMaterial = inputObject.GetComponent <Renderer>().sharedMaterial; if (sharedMaterial != null) { string inputMaterialName = sharedMaterial.name; if (sharedMaterial == null) { inputMaterialName = "new material"; newMatName = inputMaterialName; inputMaterialExists = false; } string newMaterialFolder = "Assets/Materials"; //Create a folder if it doesn't already exist. bool pathExists = AssetDatabase.IsValidFolder(newMaterialFolder); if (pathExists == false) { AssetDatabase.CreateFolder("Assets", "Materials"); } //Check if a material with the new name exists because in that case creating a material clone won't work. matNumber++; bool materialExists = DoesMaterialExist(inputMaterialName); //Create another name if it already exists. while (materialExists) { matNumber++; newMatName = GetNewMatName(inputMaterialName, matNumber); materialExists = DoesMaterialExist(newMatName); } //Create a path for the new material. string newMaterialPath = newMaterialFolder + "/" + newMatName + ".mat"; //Copy an existing material. if (inputMaterialExists) { //Get the input material path. string inputMaterialPath = GetMaterialPath(inputMaterialName); AssetDatabase.CopyAsset(inputMaterialPath, newMaterialPath); //Load the new material into memory. newMat = (Material)(AssetDatabase.LoadAssetAtPath(newMaterialPath, typeof(Material))); } //Crate a new material. else { newMat = new Material(Shader.Find("Standard")); AssetDatabase.CreateAsset(newMat, newMaterialPath); } //Assign the new material to the input object. inputObject.GetComponent <Renderer>().material = newMat; } else { Debug.Log("Select an object with a material."); } } else { Debug.Log("Select an object with a material."); } }
/// <summary> /// Duplicates a directory and renames it. The new name is the full name /// mapped from the root of the assets folder. /// </summary> public void Duplicate(string copyDirectroy) { string uniquePath = AssetDatabase.GenerateUniqueAssetPath(copyDirectroy); AssetDatabase.CopyAsset(m_Path, uniquePath); }
string ProcessTextureScaler( TextureVariationSchema schema, AddressableAssetGroup assetGroup, AddressableAssetsBuildContext aaContext) { m_SourceGroupList.Add(assetGroup); var entries = new List <AddressableAssetEntry>(assetGroup.entries); foreach (var entry in entries) { var entryPath = entry.AssetPath; if (AssetDatabase.GetMainAssetTypeAtPath(entryPath) == typeof(Texture2D)) { var fileName = Path.GetFileNameWithoutExtension(entryPath); if (string.IsNullOrEmpty(fileName)) { return("Failed to get file name for: " + entryPath); } if (!Directory.Exists("Assets/GeneratedTextures")) { Directory.CreateDirectory("Assets/GeneratedTextures"); } if (!Directory.Exists("Assets/GeneratedTextures/Texture")) { Directory.CreateDirectory("Assets/GeneratedTextures/Texture"); } var sourceTex = AssetDatabase.LoadAssetAtPath <Texture2D>(entryPath); var aiSource = AssetImporter.GetAtPath(entryPath) as TextureImporter; int maxDim = Math.Max(sourceTex.width, sourceTex.height); foreach (var pair in schema.Variations) { var newGroup = FindOrCopyGroup(assetGroup.Name + "_" + pair.label, assetGroup, aaContext.Settings, schema); var newFile = entryPath.Replace(fileName, fileName + "_variationCopy_" + pair.label); newFile = newFile.Replace("Assets/", "Assets/GeneratedTextures/"); AssetDatabase.CopyAsset(entryPath, newFile); var aiDest = AssetImporter.GetAtPath(newFile) as TextureImporter; if (aiDest == null) { var message = "failed to get TextureImporter on new texture asset: " + newFile; return(message); } float scaleFactor = pair.textureScale; float desiredLimiter = maxDim * scaleFactor; aiDest.maxTextureSize = NearestMaxTextureSize(desiredLimiter); aiDest.isReadable = true; aiDest.SaveAndReimport(); var newEntry = aaContext.Settings.CreateOrMoveEntry(AssetDatabase.AssetPathToGUID(newFile), newGroup); newEntry.address = entry.address; newEntry.SetLabel(pair.label, true); } entry.SetLabel(schema.BaselineLabel, true); } } return(string.Empty); }
string ProcessVariants(PrefabTextureVariantSchema schema, AddressableAssetGroup group, AddressableAssetsBuildContext context) { var settings = context.Settings; Directory.CreateDirectory(m_BaseDirectory); var entries = new List <AddressableAssetEntry>(group.entries); foreach (var mainEntry in entries) { if (AssetDatabase.GetMainAssetTypeAtPath(mainEntry.AssetPath) != typeof(GameObject)) { continue; } string fileName = Path.GetFileNameWithoutExtension(mainEntry.AssetPath); mainEntry.SetLabel(schema.DefaultLabel, true, true); string mainAssetPath = AssetDatabase.GUIDToAssetPath(mainEntry.guid); Hash128 assetHash = AssetDatabase.GetAssetDependencyHash(mainAssetPath); bool assetHashChanged = false; if (!m_AssetPathToHashCode.ContainsKey(mainAssetPath)) { m_AssetPathToHashCode.Add(mainAssetPath, assetHash); } else if (m_AssetPathToHashCode[mainAssetPath] != assetHash) { assetHashChanged = true; m_AssetPathToHashCode[mainAssetPath] = assetHash; } foreach (var variant in schema.Variants) { string groupDirectory = Path.Combine(m_BaseDirectory, $"{group.Name}-{Path.GetFileNameWithoutExtension(mainEntry.address)}").Replace('\\', '/'); string variantDirectory = Path.Combine(groupDirectory, variant.Label).Replace('\\', '/'); m_DirectoriesInUse.Add(groupDirectory); m_DirectoriesInUse.Add(variantDirectory); Directory.CreateDirectory(variantDirectory); var variantGroup = CreateTemporaryGroupCopy($"{group.Name}_VariantGroup_{variant.Label}", group.Schemas, settings); string newPrefabPath = mainAssetPath.Replace("Assets/", variantDirectory + '/').Replace(fileName, $"{fileName}_variant_{variant.Label}"); if (assetHashChanged || !File.Exists(newPrefabPath)) { AssetDatabase.CopyAsset(mainAssetPath, newPrefabPath); } var dependencies = AssetDatabase.GetDependencies(newPrefabPath); foreach (var dependency in dependencies) { if (AssetDatabase.GetMainAssetTypeAtPath(dependency) == typeof(GameObject)) { var gameObject = AssetDatabase.LoadAssetAtPath <GameObject>(dependency); foreach (var childRender in gameObject.GetComponentsInChildren <MeshRenderer>()) { ConvertToVariant(childRender, variantDirectory, variant, assetHashChanged); } } } var entry = settings.CreateOrMoveEntry(AssetDatabase.AssetPathToGUID(newPrefabPath), variantGroup, false, false); entry.address = mainEntry.address; entry.SetLabel(variant.Label, true, true, false); } } return(string.Empty); }
private static string CloneAndResizeToFile(PlayerSettings.WSAImageType type, PlayerSettings.WSAImageScale scale) { string texturePath = GetUWPImageTypeTexture(type, scale); if (string.IsNullOrEmpty(texturePath)) { return(string.Empty); } var iconSize = GetUWPImageTypeSize(type, scale); if (iconSize == Vector2.zero) { return(string.Empty); } if (iconSize.x == 1240 && iconSize.y == 1240 || iconSize.x == 2480 && iconSize.y == 1200) { return(texturePath); } string filePath = string.Format("{0}/{1}_{2}x{3}.png", _outputDirectoryName, type.ToString(), iconSize.x, iconSize.y); filePath = filePath.Replace(Application.dataPath, "Assets"); // Create copy of original image try { AssetDatabase.CopyAsset(texturePath, filePath); var clone = AssetDatabase.LoadAssetAtPath <Texture2D>(filePath); if (clone == null) { Debug.LogError("Unable to load texture at " + filePath); return(string.Empty); } // Resize clone to desired size TextureScale.Bilinear(clone, (int)iconSize.x, (int)iconSize.y); // Crop Color[] pix = clone.GetPixels(0, 0, (int)iconSize.x, (int)iconSize.y); clone = new Texture2D((int)iconSize.x, (int)iconSize.y, TextureFormat.ARGB32, false); clone.SetPixels(pix); clone.Apply(); var rawData = clone.EncodeToPNG(); File.WriteAllBytes(filePath, rawData); if (rawData.Length > 204800) { Debug.LogWarningFormat("{0} exceeds the minimum file size of 204,800 bytes, please use a smaller image for generating your icons.", clone.name); } } catch (Exception e) { Debug.LogError(e.Message); return(string.Empty); } return(filePath); }
//when selected public void OnSceneGUI () { if (script == null) script = (MapMagic)target; MapMagic.instance = script; if (!script.enabled) return; //checking removed terrains foreach (Chunk chunk in script.chunks.All()) if (chunk.terrain == null) script.chunks.Remove(chunk.coord); #region Drawing Selection //drawing frames if (Event.current.type == EventType.Repaint) foreach(Chunk chunk in MapMagic.instance.chunks.All()) { Handles.color = nailColor*0.8f; if (chunk.locked) Handles.color = lockColor*0.8f; DrawSelectionFrame(chunk.coord, 5f); } #endregion #region Selecting terrains if (selectionMode!=SelectionMode.none) { //disabling selection HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)); //finding aiming ray float pixelsPerPoint = 1; #if UNITY_5_4_OR_NEWER pixelsPerPoint = EditorGUIUtility.pixelsPerPoint; #endif SceneView sceneview = UnityEditor.SceneView.lastActiveSceneView; if (sceneview==null || sceneview.camera==null) return; Vector2 mousePos = Event.current.mousePosition; mousePos = new Vector2(mousePos.x/sceneview.camera.pixelWidth, 1f/pixelsPerPoint - mousePos.y/sceneview.camera.pixelHeight) * pixelsPerPoint; Ray aimRay = sceneview.camera.ViewportPointToRay(mousePos); //aiming terrain or empty place Vector3 aimPos = Vector3.zero; RaycastHit hit; if (Physics.Raycast(aimRay, out hit, Mathf.Infinity)) aimPos = hit.point; else { aimRay.direction = aimRay.direction.normalized; float aimDist = aimRay.origin.y / (-aimRay.direction.y); aimPos = aimRay.origin + aimRay.direction*aimDist; } aimPos -= MapMagic.instance.transform.position; Coord aimCoord = aimPos.FloorToCoord(MapMagic.instance.terrainSize); if (selectionMode == SelectionMode.nailing && !Event.current.alt) { //drawing selection frame Handles.color = nailColor; DrawSelectionFrame(aimCoord, width:5f); //selecting / unselecting if (Event.current.type == EventType.MouseDown && Event.current.button == 0) { if (MapMagic.instance.chunks[aimCoord]==null) //if obj not exists - nail { Undo.RegisterFullObjectHierarchyUndo(MapMagic.instance, "MapMagic Pin Terrain"); MapMagic.instance.chunks.Create(aimCoord, script, pin:true); //MapMagic.instance.terrains.maxCount++; } else { Terrain terrain = MapMagic.instance.chunks[aimCoord].terrain; if (terrain != null) Undo.DestroyObjectImmediate(terrain.gameObject); Undo.RecordObject(MapMagic.instance, "MapMagic Unpin Terrain"); MapMagic.instance.setDirty = !MapMagic.instance.setDirty; MapMagic.instance.chunks.Remove(aimCoord); //MapMagic.instance.chunks[aimCoord].pinned = false; //MapMagic.instance.terrains.maxCount--; } //if (MapMagic.instance.terrains.maxCount < MapMagic.instance.terrains.nailedHashes.Count+4) MapMagic.instance.terrains.maxCount = MapMagic.instance.terrains.nailedHashes.Count+4; //EditorUtility.SetDirty(MapMagic.instance); //already done via undo } } if (selectionMode == SelectionMode.locking && !Event.current.alt) { Chunk aimedTerrain = MapMagic.instance.chunks[aimCoord]; if (aimedTerrain != null) { //drawing selection frame Handles.color = lockColor; DrawSelectionFrame(aimCoord, width:5f); //selecting / unselecting if (Event.current.type == EventType.MouseDown && Event.current.button == 0) { Undo.RecordObject(MapMagic.instance, "MapMagic Lock Terrain"); MapMagic.instance.setDirty = !MapMagic.instance.setDirty; aimedTerrain.locked = !aimedTerrain.locked; //EditorUtility.SetDirty(MapMagic.instance); //already done via undo } } } if (selectionMode == SelectionMode.exporting && !Event.current.alt) { Chunk aimedTerrain = MapMagic.instance.chunks[aimCoord]; if (aimedTerrain != null) { //drawing selection frame Handles.color = exportColor; DrawSelectionFrame(aimCoord, width:5f); //exporting if (Event.current.type == EventType.MouseDown && Event.current.button == 0) { string path= UnityEditor.EditorUtility.SaveFilePanel( "Export Terrain Data", "", "TerrainData.asset", "asset"); if (path!=null && path.Length!=0) { path = path.Replace(Application.dataPath, "Assets"); if (!path.Contains("Assets")) { Debug.LogError("MapMagic: Path is out of the Assets folder"); return; } if (AssetDatabase.LoadAssetAtPath(path, typeof(TerrainData)) as TerrainData == aimedTerrain.terrain.terrainData) { Debug.Log("MapMagic: this terrain was already exported at the given path"); return; } Terrain terrain = aimedTerrain.terrain; float[,,] splats = terrain.terrainData.GetAlphamaps(0,0,terrain.terrainData.alphamapResolution, terrain.terrainData.alphamapResolution); //else splats = new float[terrain.terrainData.alphamapResolution,terrain.terrainData.alphamapResolution,1]; if (terrain.terrainData.alphamapLayers==1 && terrain.terrainData.alphamapTextures[0].width==2) { terrain.terrainData.splatPrototypes = new SplatPrototype[0]; terrain.terrainData.SetAlphamaps(0,0,new float[0,0,0]); } AssetDatabase.DeleteAsset(path); if (AssetDatabase.Contains(terrain.terrainData)) { AssetDatabase.CopyAsset(AssetDatabase.GetAssetPath(terrain.terrainData),path); terrain.terrainData = AssetDatabase.LoadAssetAtPath(path, typeof(TerrainData)) as TerrainData; if (terrain.GetComponent<TerrainCollider>()!=null) terrain.GetComponent<TerrainCollider>().terrainData = terrain.terrainData; } else AssetDatabase.CreateAsset(terrain.terrainData, path); terrain.terrainData.SetAlphamaps(0,0,splats); AssetDatabase.SaveAssets(); } } } } //redrawing scene by moving temp object if (script.sceneRedrawObject==null) { script.sceneRedrawObject = new GameObject(); script.sceneRedrawObject.hideFlags = HideFlags.HideInHierarchy; } script.sceneRedrawObject.transform.position = aimPos; } #endregion }
private static void ResizeImages() { try { EditorUtility.DisplayProgressBar("Generating images", "Checking Texture Importers", 0); // Check if we need to reimport the original textures, for enabling reading. if (CheckTextureImporter(_originalAppIconPath) || CheckTextureImporter(_originalSplashImagePath)) { AssetDatabase.Refresh(); } if (!Directory.Exists(_outputDirectoryName)) { Directory.CreateDirectory(_outputDirectoryName); } else { foreach (string file in Directory.GetFiles(_outputDirectoryName)) { File.Delete(file); } } // Create a copy of the original images string outputDirectoryBasePath = _outputDirectoryName; outputDirectoryBasePath = outputDirectoryBasePath.Replace(Application.dataPath, "Assets"); _newAppIconPath = outputDirectoryBasePath + "/BaseIcon_1240x1240.png"; _newSplashImagePath = outputDirectoryBasePath + "/BaseSplashImage_2480x1200.png"; AssetDatabase.CopyAsset(_originalAppIconPath, _newAppIconPath); AssetDatabase.CopyAsset(_originalSplashImagePath, _newSplashImagePath); // Set Default Icon in Player Settings (Multiple platforms, can be overridden per platform) PlayerSettings.SetIconsForTargetGroup(BuildTargetGroup.Unknown, new[] { AssetDatabase.LoadAssetAtPath <Texture2D>(_newAppIconPath) }); PlayerSettings.virtualRealitySplashScreen = AssetDatabase.LoadAssetAtPath <Texture2D>(_newSplashImagePath); // Loop through available types and scales for UWP var types = Enum.GetValues(typeof(PlayerSettings.WSAImageType)).Cast <PlayerSettings.WSAImageType>().ToList(); var scales = Enum.GetValues(typeof(PlayerSettings.WSAImageScale)).Cast <PlayerSettings.WSAImageScale>().ToList(); float progressTotal = types.Count * scales.Count; float progress = 0; bool canceled = false; foreach (var type in types) { if (canceled) { break; } foreach (var scale in scales) { PlayerSettings.WSA.SetVisualAssetsImage(CloneAndResizeToFile(type, scale), type, scale); progress++; if (EditorUtility.DisplayCancelableProgressBar("Generating images", string.Format("Generating resized images {0} of {1}", progress, progressTotal), progress / progressTotal)) { canceled = true; break; } } } AssetDatabase.SaveAssets(); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); if (canceled) { EditorUtility.DisplayDialog("Generation canceled", string.Format("{0} Images of {1} were resized and updated in the Player Settings.", progress, progressTotal), "Ok"); } else { EditorUtility.DisplayDialog("Images resized!", "All images were resized and updated in the Player Settings", "Ok"); } EditorUtility.ClearProgressBar(); } catch (Exception e) { Debug.LogError(e.Message); EditorUtility.ClearProgressBar(); } }
void OnGUI() { if (Event.current.type == EventType.Layout) { if (newAssetPath != null) { GUIUtility.keyboardControl = 0; GUIUtility.hotControl = 0; assetsPaths = newAssetPath; newAssetPath = null; } if (assetsPaths == null) { assetsPaths = "\n"; } else { if (!assetsPaths.EndsWith("\n")) { assetsPaths = assetsPaths + "\n"; } } if (assetsPaths.IndexOf('\\') >= 0) { assetsPaths = assetsPaths.Replace('\\', '/'); } if (destinationFolder != null) { string destpath = AssetDatabase.GetAssetPath(destinationFolder); if (string.IsNullOrEmpty(destpath)) { destinationFolder = null; } else if (!System.IO.Directory.Exists(destpath)) { destpath = destpath.Substring(0, destpath.LastIndexOf('/')); destinationFolder = AssetDatabase.LoadMainAssetAtPath(destpath); } } } GUILayout.BeginHorizontal("Toolbar"); GUILayout.Label(""); GUILayout.EndHorizontal(); templateAsset = EditorGUILayout.ObjectField("Template Asset", templateAsset, typeof(Object), false); destinationFolder = EditorGUILayout.ObjectField("Destination Folder", destinationFolder, typeof(Object), false); GUILayout.Label("Assets to be imported (Drag and drop, or write full path)"); GUILayout.Space(2); scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition); assetsPaths = EditorGUILayout.TextArea(assetsPaths); Event evt = Event.current; Rect drop_area = GUILayoutUtility.GetLastRect(); switch (evt.type) { case EventType.DragUpdated: case EventType.DragPerform: if (!drop_area.Contains(evt.mousePosition)) { return; } DragAndDrop.visualMode = DragAndDropVisualMode.Copy; if (evt.type == EventType.DragPerform) { DragAndDrop.AcceptDrag(); StringBuilder sb = new StringBuilder(); foreach (var path in assetsPaths.Split('\n', '\r')) { if (string.IsNullOrEmpty(path)) { continue; } sb.AppendFormat("{0}\n", path.ToString()); } foreach (var path in DragAndDrop.paths) { if (string.IsNullOrEmpty(path)) { continue; } sb.AppendFormat("{0}\n", path.ToString()); } newAssetPath = sb.ToString(); } break; } EditorGUILayout.EndScrollView(); if (GUILayout.Button("Import")) { var start = System.DateTime.Now; string destpath; if (destinationFolder != null) { destpath = AssetDatabase.GetAssetPath(destinationFolder); } else { destpath = AssetDatabase.GetAssetPath(templateAsset); destpath = destpath.Substring(0, destpath.LastIndexOf('/')); } List <Object> assets = new List <Object>(); foreach (var assetPath in assetsPaths.Split('\n', '\r')) { if (string.IsNullOrEmpty(assetPath)) { continue; } var assetDest = destpath + assetPath.Substring(assetPath.LastIndexOf('/')); assetDest = AssetDatabase.GenerateUniqueAssetPath(assetDest); AssetDatabase.CopyAsset(AssetDatabase.GetAssetPath(templateAsset.GetInstanceID()), assetDest); System.IO.File.Copy(assetPath, assetDest, true); //AssetDatabase.ImportAsset(assetDest); assets.Add(AssetDatabase.LoadAssetAtPath(assetDest, templateAsset.GetType())); } AssetDatabase.SaveAssets(); Selection.instanceIDs = new int[0]; Selection.objects = assets.ToArray(); AssetDatabase.Refresh(); Debug.Log(string.Format("Asset Importer: Importing {0} assets took {1} seconds", assets.Count, (System.DateTime.Now - start).TotalSeconds)); } GUILayout.Space(6); }
public static bool CopyTextureToPng(string source, string dest) { AssetDatabase.DeleteAsset(dest); string sourceExtension = System.IO.Path.GetExtension(source); if (string.Compare(sourceExtension, ".png", true) != 0) { var index = dest.LastIndexOf('/'); string temp = dest.Substring(0, index + 1) + "TEMP_" + dest.Substring(index + 1) + sourceExtension; AssetDatabase.DeleteAsset(temp); if (!AssetDatabase.CopyAsset(source, temp)) { Debug.LogError(string.Format("CopyTextureToPng error: Couldn't copy {0} to temp {1}", source, temp)); return(false); } AssetDatabase.ImportAsset(temp); var importer = TextureImporter.GetAtPath(temp) as TextureImporter; if (!importer.isReadable || importer.textureFormat != TextureImporterFormat.ARGB32) { importer.isReadable = true; importer.textureFormat = TextureImporterFormat.ARGB32; AssetDatabase.ImportAsset(temp); } var tex = AssetDatabase.LoadAssetAtPath(temp, typeof(Texture2D)) as Texture2D; if (tex == null) { Debug.LogError("DAMNABBIT asset not readable: " + temp); return(false); } System.IO.File.WriteAllBytes(dest, tex.EncodeToPNG()); AssetDatabase.ImportAsset(dest); //var destTex = Texture2D.Instantiate(tex) as Texture2D; //var destTex = new Texture2D(tex.width, tex.height, tex.format, tex.mipmapCount > 0); //destTex.anisoLevel = tex.anisoLevel; //destTex.filterMode = tex.filterMode; //destTex.mipMapBias = tex.mipMapBias; //destTex.wrapMode = tex.wrapMode; //destTex.SetPixels32(tex.GetPixels32()); //AssetDatabase.CreateAsset(destTex, dest); var tempimporter = TextureImporter.GetAtPath(temp) as TextureImporter; var destimporter = TextureImporter.GetAtPath(dest) as TextureImporter; var settings = new TextureImporterSettings(); tempimporter.ReadTextureSettings(settings); destimporter.SetTextureSettings(settings); destimporter.normalmap = false; destimporter.isReadable = true; AssetDatabase.ImportAsset(dest); AssetDatabase.DeleteAsset(temp); } else { if (!AssetDatabase.CopyAsset(source, dest)) { Debug.LogError(string.Format("CopyTextureToPng error: Couldn't copy {0} to {1}", source, dest)); return(false); } AssetDatabase.ImportAsset(dest); } return(true); }
// Update target platforms public static void UpdatePlatformSpriteCollection(tk2dSpriteCollection source, tk2dSpriteCollection target, string dataPath, bool root, float scale, string platformName) { tk2dEditor.SpriteCollectionEditor.SpriteCollectionProxy proxy = new tk2dEditor.SpriteCollectionEditor.SpriteCollectionProxy(source); // Restore old sprite collection proxy.spriteCollection = target.spriteCollection; proxy.atlasTextures = target.atlasTextures; proxy.atlasMaterials = target.atlasMaterials; proxy.altMaterials = target.altMaterials; // This must always be zero, as children cannot have nested platforms. // That would open the door to a lot of unnecessary insanity proxy.platforms = new List <tk2dSpriteCollectionPlatform>(); // Update atlas sizes proxy.atlasWidth = (int)(proxy.atlasWidth * scale); proxy.atlasHeight = (int)(proxy.atlasHeight * scale); proxy.maxTextureSize = (int)(proxy.maxTextureSize * scale); proxy.forcedTextureWidth = (int)(proxy.forcedTextureWidth * scale); proxy.forcedTextureHeight = (int)(proxy.forcedTextureHeight * scale); proxy.globalScale = 1.0f / scale; // Don't bother changing stuff on the root object // The root object is the one that the sprite collection is defined on initially if (!root) { // Update textures foreach (tk2dSpriteCollectionDefinition param in proxy.textureParams) { if (param.texture == null) { continue; } string path = AssetDatabase.GetAssetPath(param.texture); string platformTexture = FindAssetForPlatform(platformName, path, textureExtensions); if (platformTexture.Length == 0) { LogNotFoundError(platformName, param.texture.name, "texture"); } else { Texture2D tex = AssetDatabase.LoadAssetAtPath(platformTexture, typeof(Texture2D)) as Texture2D; if (tex == null) { Debug.LogError("Unable to load platform specific texture '" + platformTexture + "'"); } else { param.texture = tex; } } // Handle spritesheets. Odd coordinates could cause issues if (param.extractRegion) { param.regionX = (int)(param.regionX * scale); param.regionY = (int)(param.regionY * scale); param.regionW = (int)(param.regionW * scale); param.regionH = (int)(param.regionH * scale); } if (param.anchor == tk2dSpriteCollectionDefinition.Anchor.Custom) { param.anchorX = (int)(param.anchorX * scale); param.anchorY = (int)(param.anchorY * scale); } if (param.customSpriteGeometry) { foreach (tk2dSpriteColliderIsland geom in param.geometryIslands) { for (int p = 0; p < geom.points.Length; ++p) { geom.points[p] *= scale; } } } else if (param.dice) { param.diceUnitX = (int)(param.diceUnitX * scale); param.diceUnitY = (int)(param.diceUnitY * scale); } if (param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Polygon) { foreach (tk2dSpriteColliderIsland geom in param.polyColliderIslands) { for (int p = 0; p < geom.points.Length; ++p) { geom.points[p] *= scale; } } } else if (param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.BoxCustom) { param.boxColliderMax *= scale; param.boxColliderMin *= scale; } for (int i = 0; i < param.attachPoints.Count; ++i) { param.attachPoints[i].position = param.attachPoints[i].position * scale; } } } // We ALWAYS duplicate fonts if (target.fonts == null) { target.fonts = new tk2dSpriteCollectionFont[0]; } for (int i = 0; i < proxy.fonts.Count; ++i) { tk2dSpriteCollectionFont font = proxy.fonts[i]; if (!font.InUse || font.texture == null || font.data == null || font.editorData == null || font.bmFont == null) { continue; // not valid for some reason or other } bool needFontData = true; bool needFontEditorData = true; bool hasCorrespondingData = i < target.fonts.Length && target.fonts[i] != null; if (hasCorrespondingData) { tk2dSpriteCollectionFont targetFont = target.fonts[i]; if (targetFont.data != null) { font.data = targetFont.data; needFontData = false; } if (targetFont.editorData != null) { font.editorData = targetFont.editorData; needFontEditorData = false; } } string bmFontPath = AssetDatabase.GetAssetPath(font.bmFont); string texturePath = AssetDatabase.GetAssetPath(font.texture); if (!root) { // find platform specific versions bmFontPath = FindAssetForPlatform(platformName, bmFontPath, fontExtensions); texturePath = FindAssetForPlatform(platformName, texturePath, textureExtensions); if (bmFontPath.Length != 0 && texturePath.Length == 0) { // try to find a texture tk2dEditor.Font.Info fontInfo = tk2dEditor.Font.Builder.ParseBMFont(bmFontPath); if (fontInfo != null) { texturePath = System.IO.Path.GetDirectoryName(bmFontPath).Replace('\\', '/') + "/" + System.IO.Path.GetFileName(fontInfo.texturePaths[0]); } } if (bmFontPath.Length == 0) { LogNotFoundError(platformName, font.bmFont.name, "font"); } if (texturePath.Length == 0) { LogNotFoundError(platformName, font.texture.name, "texture"); } if (bmFontPath.Length == 0 || texturePath.Length == 0) { continue; // not found } // load the assets font.bmFont = AssetDatabase.LoadAssetAtPath(bmFontPath, typeof(UnityEngine.Object)); font.texture = AssetDatabase.LoadAssetAtPath(texturePath, typeof(Texture2D)) as Texture2D; } string targetDir = System.IO.Path.GetDirectoryName(AssetDatabase.GetAssetPath(target)); // create necessary assets if (needFontData) { string srcPath = AssetDatabase.GetAssetPath(font.data); string destPath = AssetDatabase.GenerateUniqueAssetPath(GetCopyAtTargetPath(platformName, targetDir, srcPath)); AssetDatabase.CopyAsset(srcPath, destPath); AssetDatabase.Refresh(); font.data = AssetDatabase.LoadAssetAtPath(destPath, typeof(tk2dFontData)) as tk2dFontData; } if (needFontEditorData) { string srcPath = AssetDatabase.GetAssetPath(font.editorData); string destPath = AssetDatabase.GenerateUniqueAssetPath(GetCopyAtTargetPath(platformName, targetDir, srcPath)); AssetDatabase.CopyAsset(srcPath, destPath); AssetDatabase.Refresh(); font.editorData = AssetDatabase.LoadAssetAtPath(destPath, typeof(tk2dFont)) as tk2dFont; } if (font.editorData.bmFont != font.bmFont || font.editorData.texture != font.texture || font.editorData.data != font.data) { font.editorData.bmFont = font.bmFont; font.editorData.texture = font.texture; font.editorData.data = font.data; EditorUtility.SetDirty(font.editorData); } } proxy.CopyToTarget(target); }
/// <summary> /// 注意如果copy文件夹不存在,则copy不生效 /// 需要相对路径,带文件名后缀 /// eg: /// 移动mat /// 从:Assets/ArtRes/Role/Res\hg/Materials/hgmat.mat /// 到Assets/ArtRes/Role/TempAsset/hg/Materials/hgmat.mat /// </summary> /// <param name="path">Path.</param> /// <param name="newpath">Newpath.需要相对路径</param> public static void CopyAsset(string path, string newpath) { AssetDatabase.CopyAsset(path, newpath); }
/// <summary> /// Copies asset of type T to specified persistent path /// </summary> /// <remarks> /// If the specified path does not exist, it will be created using EP.CreatePersistentPath. /// The asset name will be a unique derivative of the name of the asset object. /// If assetSuffix is not specified the suffix corresponding to the asset type will be used. /// /// WARNING: When AssetDatabase.StartAssetEditing() has been called, AssetDatabase.CopyAsset /// and PrefabUtility.SaveAsPrefabAsset will not modify AssetDatabase, in which case the returned /// asset reference will be the asset argument. /// </remarks> /// <typeparam name="T">Asset type</typeparam> /// <param name="asset">Asset to be copied</param> /// <param name="assetPath">Path relative to persistent folder where asset will be created</param> /// <param name="assetSuffix">Optional override of default suffix for asset type</param> /// <returns>The asset copy, or the origin of AssetDatabase has not been updated</returns> public static T CopyAssetToPath <T>(T asset, string assetPath, string assetSuffix = null) where T : Object { // Ensure that the asset path folders exist EP.CreatePersistentPath(assetPath); T assetCopy = null; if (useEditorAction) { #if UNITY_EDITOR // Match asset and file type, and ensure that asset will be unique if (assetSuffix == null) { assetSuffix = ".asset"; var oldPath = AssetDatabase.GetAssetPath(asset); if (oldPath != null) { // Preserve existing file type (important for images and models) assetSuffix = oldPath.Substring(oldPath.LastIndexOf('.')); } else { // Use default file type for asset type // https://docs.unity3d.com/ScriptReference/AssetDatabase.CreateAsset.html if (asset is GameObject) { assetSuffix = ".prefab"; } if (asset is Material) { assetSuffix = ".mat"; } if (asset is Cubemap) { assetSuffix = ".cubemap"; } if (asset is GUISkin) { assetSuffix = ".GUISkin"; } if (asset is Animation) { assetSuffix = ".anim"; } // TODO: Cover other specialized types such as giparams } } var newPath = "Assets/" + assetPath + "/" + asset.name + assetSuffix; newPath = AssetDatabase.GenerateUniqueAssetPath(newPath); // WARNING: (Unity2019.4 undocumented) AssetDatabase.GenerateUniqueAssetPath will trim name spaces // Copy asset to new path // NOTE: The goal is to keep the original asset in place, // so AssetDatabase.ExtractAsset is not used. if (asset is GameObject) { var gameObject = asset as GameObject; if (PrefabUtility.GetPrefabAssetType(gameObject) == PrefabAssetType.NotAPrefab) { assetCopy = PrefabUtility.SaveAsPrefabAsset(gameObject, newPath) as T; } else { // NOTE: PrefabUtility.SaveAsPrefabAsset cannot save an asset reference as a prefab var copyObject = PrefabUtility.InstantiatePrefab(gameObject) as GameObject; // NOTE: Root must be unpacked, otherwise this will yield a prefab variant PrefabUtility.UnpackPrefabInstance(copyObject, PrefabUnpackMode.OutermostRoot, InteractionMode.AutomatedAction); assetCopy = PrefabUtility.SaveAsPrefabAsset(copyObject, newPath) as T; EP.Destroy(copyObject); } } else { // IMPORTANT: SubAssets must be instantiated, otherise AssetDatabase.CreateAsset(asset, newPath) will fail // with error: "Couldn't add object to asset file because the Mesh [] is already an asset at [].fbx" // NOTE: AssetDatabase.ExtractAsset will register as a modification of model import settings if (AssetDatabase.IsSubAsset(asset)) { AssetDatabase.CreateAsset(Object.Instantiate(asset), newPath); } else { AssetDatabase.CopyAsset(AssetDatabase.GetAssetPath(asset), newPath); } } assetCopy = AssetDatabase.LoadAssetAtPath <T>(newPath); #endif } else { Debug.LogWarning("Runtime asset copying is not implemented"); // TODO: For runtime version simply copy the file! } if (!assetCopy) { return(asset); // Continue to use asset at previous path } return(assetCopy as T); }
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { //EditorGUI.PropertyField(position, property, label); var attr = this.attr; var go = (property.serializedObject.targetObject as Component).gameObject; if (go == null) { return; } var pth = AssetDatabase.GetAssetPath(go); if (string.IsNullOrEmpty(pth) == true) { return; } var assetPath = System.IO.Path.GetDirectoryName(pth); var screensMarker = "Screens"; if (assetPath.EndsWith(screensMarker) == true) { assetPath = assetPath.Remove(assetPath.Length - screensMarker.Length); assetPath += "Layouts"; } attr.filterDir = assetPath; var target = property; var so = property.serializedObject; var targetObject = so.targetObject; var targetPath = target.propertyPath; EditorGUI.LabelField(position, label); position.x += EditorGUIUtility.labelWidth; position.width -= EditorGUIUtility.labelWidth; if (GUILayoutExt.DrawDropdown(position, new GUIContent(target.objectReferenceValue != null ? EditorHelpers.StringToCaption(target.objectReferenceValue.name) : attr.noneOption), FocusType.Passive, target.objectReferenceValue) == true) { var rect = position; var vector = GUIUtility.GUIToScreenPoint(new Vector2(rect.x, rect.y)); rect.x = vector.x; rect.y = vector.y; var popup = new Popup() { title = attr.menuName, autoClose = true, screenRect = new Rect(rect.x, rect.y + rect.height, rect.width, 200f) }; var objects = AssetDatabase.FindAssets("t:" + (attr.filterType != null ? attr.filterType : "Object"), attr.filterDir == null ? null : new [] { attr.filterDir }); var allObjects = Resources.LoadAll <GameObject>("").Where(x => x.GetComponent <WindowLayout>() != null && x.GetComponent <TemplateMarker>() != null).ToArray(); for (int i = 0; i < allObjects.Length; ++i) { var idx = i; popup.Item("Clone Template/" + allObjects[i].name, null, searchable: true, action: (item) => { var p = AssetDatabase.GetAssetPath(allObjects[idx]); var newPath = AssetDatabase.GenerateUniqueAssetPath(assetPath + "/" + allObjects[idx].name + ".prefab"); AssetDatabase.CopyAsset(p, newPath); AssetDatabase.ImportAsset(newPath, ImportAssetOptions.ForceUpdate); AssetDatabase.ForceReserializeAssets(new [] { newPath }, ForceReserializeAssetsOptions.ReserializeAssetsAndMetadata); var newGo = AssetDatabase.LoadAssetAtPath <GameObject>(newPath); Object.DestroyImmediate(newGo.GetComponent <TemplateMarker>(), true); AssetDatabase.ForceReserializeAssets(new [] { newPath }, ForceReserializeAssetsOptions.ReserializeAssetsAndMetadata); so = new SerializedObject(targetObject); so.Update(); so.FindProperty(targetPath).objectReferenceValue = newGo.GetComponent <WindowLayout>(); so.ApplyModifiedProperties(); }, order: -1); } if (string.IsNullOrEmpty(attr.noneOption) == false) { popup.Item(attr.noneOption, null, searchable: false, action: (item) => { so = new SerializedObject(targetObject); so.Update(); so.FindProperty(targetPath).objectReferenceValue = null; so.ApplyModifiedProperties(); }, order: -1); } for (int i = 0; i < objects.Length; ++i) { var path = AssetDatabase.GUIDToAssetPath(objects[i]); var asset = AssetDatabase.LoadAssetAtPath <GameObject>(path); if (asset.GetComponent <WindowLayout>() == null) { continue; } popup.Item(EditorHelpers.StringToCaption(asset.name), () => { so = new SerializedObject(targetObject); so.Update(); so.FindProperty(targetPath).objectReferenceValue = asset.GetComponent <WindowLayout>(); so.ApplyModifiedProperties(); }); } popup.Show(); } }
/// <summary> /// Duplicates the current directory in the same place but gives it a unique /// name by adding an incrementing number at the end. /// </summary> public void Duplicate() { string copyDir = AssetDatabase.GenerateUniqueAssetPath(m_Path); AssetDatabase.CopyAsset(m_Path, copyDir); }
void OnGUI() { this.minSize = new Vector2(320, 500); #region fonts variables var bold = new GUIStyle("label"); var boldFold = new GUIStyle("foldout"); bold.fontStyle = FontStyle.Bold; bold.fontSize = 14; boldFold.fontStyle = FontStyle.Bold; var Slim = new GUIStyle("label"); Slim.fontStyle = FontStyle.Normal; Slim.fontSize = 10; var style = new GUIStyle("label"); style.wordWrap = true; #endregion fonts variables if (_SlotsAnatomyLibrary == null && EditorVariables.SlotsAnatomyLibraryObj) { _SlotsAnatomyLibrary = EditorVariables.SlotsAnatomyLibraryObj.GetComponent <DK_SlotsAnatomyLibrary>(); } GUILayout.Space(5); using (new Horizontal()) { GUI.color = Color.white; GUILayout.Label("Modify Anatomy Slots", "toolbarbutton", GUILayout.ExpandWidth(true)); GUI.color = Red; // if ( GUILayout.Button ( "X", "toolbarbutton", GUILayout.ExpandWidth (false))) { // } } GUILayout.Space(5); GUI.color = Color.white; if (Helper) { GUILayout.TextField("The Anatomy Parts are used during the creation of the UMA Model. " + "The engine check all the Anatomy parts to select the torso and its slot and overlays. " + "Each part determines what slot Element will be generated to be placed on it. " + "It is also used by the Overlay Element to associate with a slot.", 300, style, GUILayout.ExpandWidth(true), GUILayout.ExpandWidth(true)); } if (SelectedAnaPart != null) { using (new Horizontal()) { GUI.color = Color.white; GUILayout.Label("Anatomy Part :", GUILayout.ExpandWidth(false)); if (NewAnatomyName != "") { GUI.color = Green; } else { GUI.color = Red; } NewAnatomyName = GUILayout.TextField(NewAnatomyName, 50, GUILayout.ExpandWidth(true)); if (GUILayout.Button("Change", GUILayout.ExpandWidth(false))) { Debug.Log("Anatomy " + SelectedAnaPart.name + " changed to " + NewAnatomyName + "."); DK_SlotsAnatomyElement _DK_SlotsAnatomyElement = SelectedAnaPart.GetComponent <DK_SlotsAnatomyElement>(); _DK_SlotsAnatomyElement.dk_SlotsAnatomyElement.dk_SlotsAnatomyName = NewAnatomyName; SelectedAnaPart.name = NewAnatomyName; // SelectedAnaPart.gameObject.name = NewAnatomyName; Selection.activeObject.name = NewAnatomyName; AssetDatabase.RenameAsset(AssetDatabase.GetAssetPath(Selection.activeObject), NewAnatomyName + ".prefab"); Debug.Log(AssetDatabase.GetAssetPath(Selection.activeObject)); EditorUtility.SetDirty(SelectedAnaPart.gameObject); AssetDatabase.SaveAssets(); } } GUI.color = Color.yellow; if (Helper) { GUILayout.TextField("You can link 2 anatomy parts and configure a slot to remove the linked Anatomy part (ex.: Remove the feet when generating a boots slot).", 256, style, GUILayout.ExpandWidth(true), GUILayout.ExpandWidth(true)); } if (SelectedAnaPart != null) { using (new Horizontal()) { GUI.color = Color.white; GUILayout.Label("Link to :", GUILayout.ExpandWidth(false)); if (SelectedAnaPart.GetComponent <DK_SlotsAnatomyElement>().dk_SlotsAnatomyElement.Place != null) { GUILayout.TextField(SelectedAnaPart.GetComponent <DK_SlotsAnatomyElement>().dk_SlotsAnatomyElement.Place.name, 50, GUILayout.ExpandWidth(true)); } else { GUI.color = Color.white; GUILayout.Label("No Link", GUILayout.ExpandWidth(true)); } if (!ChooseLink) { if (GUILayout.Button("Select", GUILayout.ExpandWidth(false))) { ChooseLink = true; } GUI.color = Red; if (GUILayout.Button("X", GUILayout.ExpandWidth(false))) { SelectedAnaPart.GetComponent <DK_SlotsAnatomyElement>().dk_SlotsAnatomyElement.Place = null; } } else { GUI.color = Color.yellow; GUILayout.Label("Click an Element from the list bellow.", GUILayout.ExpandWidth(true)); GUI.color = Color.white; if (GUILayout.Button("Cancel", GUILayout.ExpandWidth(false))) { ChooseLink = false; } } } } // Gender GUI.color = Color.yellow; if (SelectedAnaPart != null && Helper) { GUILayout.TextField("You can specify a Gender or let it be usable by both (Both is recommended).", 256, style, GUILayout.ExpandWidth(true), GUILayout.ExpandWidth(true)); } if (SelectedAnaPart != null) { using (new Horizontal()) { if (NewPresetGender == "Both") { GUI.color = Green; } else { GUI.color = Color.gray; } if (GUILayout.Button("Both", GUILayout.ExpandWidth(true))) { NewPresetGender = "Both"; DK_Race = SelectedAnaPart.GetComponent("DK_Race") as DK_Race; DK_Race.Gender = NewPresetGender; DK_SlotsAnatomyElement _DK_SlotsAnatomyElement = SelectedAnaPart.GetComponent <DK_SlotsAnatomyElement>(); _DK_SlotsAnatomyElement.dk_SlotsAnatomyElement.ForGender = NewPresetGender; EditorUtility.SetDirty(SelectedAnaPart.gameObject); AssetDatabase.SaveAssets(); } if (NewPresetGender == "Female") { GUI.color = Green; } else { GUI.color = Color.gray; } if (GUILayout.Button("Female", GUILayout.ExpandWidth(true))) { NewPresetGender = "Female"; DK_Race = SelectedAnaPart.GetComponent("DK_Race") as DK_Race; DK_Race.Gender = NewPresetGender; DK_SlotsAnatomyElement _DK_SlotsAnatomyElement = SelectedAnaPart.GetComponent <DK_SlotsAnatomyElement>(); _DK_SlotsAnatomyElement.dk_SlotsAnatomyElement.ForGender = NewPresetGender; EditorUtility.SetDirty(SelectedAnaPart.gameObject); AssetDatabase.SaveAssets(); } if (NewPresetGender == "Male") { GUI.color = Green; } else { GUI.color = Color.gray; } if (GUILayout.Button("Male", GUILayout.ExpandWidth(true))) { NewPresetGender = "Male"; DK_Race = SelectedAnaPart.GetComponent("DK_Race") as DK_Race; DK_Race.Gender = NewPresetGender; DK_SlotsAnatomyElement _DK_SlotsAnatomyElement = SelectedAnaPart.GetComponent <DK_SlotsAnatomyElement>(); _DK_SlotsAnatomyElement.dk_SlotsAnatomyElement.ForGender = NewPresetGender; EditorUtility.SetDirty(SelectedAnaPart.gameObject); AssetDatabase.SaveAssets(); } } } GUI.color = Color.yellow; if (Helper) { GUILayout.TextField("Select the race(s) for the Anatomy Part.", 256, style, GUILayout.ExpandWidth(true), GUILayout.ExpandWidth(true)); } if (Selection.activeGameObject != null) { using (new Horizontal()) { GUI.color = Color.white; GUILayout.Label("For Race :", GUILayout.ExpandWidth(false)); if (NewAnatomyName != "") { GUI.color = Green; } else { GUI.color = Red; } if (GUILayout.Button("Open List", GUILayout.ExpandWidth(true))) { OpenRaceSelectEditor(); } GUILayout.Label("Spawn %", GUILayout.ExpandWidth(false)); if (_SpawnPerct != "" && _SpawnPerct != null) { _SpawnPerct = GUILayout.TextField(_SpawnPerct, 5, GUILayout.Width(30)); _SpawnPerct = Regex.Replace(_SpawnPerct, "[^0-9]", ""); } if (_SpawnPerct == "") { _SpawnPerct = "1"; } if (Convert.ToInt32(_SpawnPerct) > 100) { _SpawnPerct = "100"; } if (GUILayout.Button("Change", GUILayout.ExpandWidth(false))) { DK_Race _DK_Race = Selection.activeGameObject.GetComponent <DK_Race>(); Selection.activeGameObject.GetComponent <DK_SlotsAnatomyData>().SpawnPerct = Convert.ToInt32(_SpawnPerct); EditorUtility.SetDirty(SelectedAnaPart.gameObject); AssetDatabase.SaveAssets(); } } } GUILayout.Space(5); // Head ? GUI.color = Color.yellow; if (Helper) { GUILayout.TextField("The 'Head' part is used by the generator to place all the face elements such as the hair or the beard. Beware You need to assign a single 'Head' Anatomy part to only one slot.", 256, style, GUILayout.ExpandWidth(true), GUILayout.ExpandWidth(true)); } using (new Horizontal()) { GUI.color = Color.white; GUILayout.Label("Is ", GUILayout.ExpandWidth(false)); if (OverlayType == "Is Head Part") { GUI.color = Green; } else { GUI.color = Color.gray; } if (GUILayout.Button("Head", GUILayout.ExpandWidth(true))) { OverlayType = "Is Head Part"; DK_Race = SelectedAnaPart.GetComponent("DK_Race") as DK_Race; DK_Race.OverlayType = OverlayType; EditorUtility.SetDirty(SelectedAnaPart.gameObject); AssetDatabase.SaveAssets(); } GUI.color = Color.white; GUILayout.Label("? Is ", GUILayout.ExpandWidth(false)); if (OverlayType == "Is Head Elem") { GUI.color = Green; } else { GUI.color = Color.gray; } if (GUILayout.Button("Head Elem", GUILayout.ExpandWidth(true))) { OverlayType = "Is Head Elem"; DK_Race = SelectedAnaPart.GetComponent("DK_Race") as DK_Race; DK_Race.OverlayType = OverlayType; EditorUtility.SetDirty(SelectedAnaPart.gameObject); AssetDatabase.SaveAssets(); } GUI.color = Color.white; GUILayout.Label("? Is ", GUILayout.ExpandWidth(false)); if (OverlayType == "Is Torso Part") { GUI.color = Green; } else { GUI.color = Color.gray; } if (GUILayout.Button("Torso", GUILayout.ExpandWidth(true))) { OverlayType = "Is Torso Part"; DK_Race = SelectedAnaPart.GetComponent("DK_Race") as DK_Race; DK_Race.OverlayType = OverlayType; EditorUtility.SetDirty(SelectedAnaPart.gameObject); AssetDatabase.SaveAssets(); } GUI.color = Color.white; GUILayout.Label("?", GUILayout.ExpandWidth(false)); } // Overlay Type GUI.color = Color.yellow; if (Helper) { GUILayout.TextField("The Overlay Type is used by the Generator during the Model's creation. " + "All the 'Naked body parts' must be of the 'Flesh' Type, the Head slot must be of the 'Face' type.", 256, style, GUILayout.ExpandWidth(true), GUILayout.ExpandWidth(true)); } using (new Horizontal()) { GUI.color = Color.white; GUILayout.Label("Overlay Type :", GUILayout.ExpandWidth(false)); if (OverlayType == "Flesh") { GUI.color = Green; } else { GUI.color = Color.gray; } if (GUILayout.Button("Flesh", GUILayout.ExpandWidth(true))) { OverlayType = "Flesh"; DK_Race _DK_Race = SelectedAnaPart.gameObject.GetComponent <DK_Race>(); _DK_Race.OverlayType = "Flesh"; EditorUtility.SetDirty(SelectedAnaPart.gameObject); AssetDatabase.SaveAssets(); } if (OverlayType == "Face") { GUI.color = Green; } else { GUI.color = Color.gray; } if (GUILayout.Button("Face", GUILayout.ExpandWidth(true))) { OverlayType = "Face"; DK_Race _DK_Race = SelectedAnaPart.gameObject.GetComponent <DK_Race>(); _DK_Race.OverlayType = "Face"; EditorUtility.SetDirty(SelectedAnaPart.gameObject); AssetDatabase.SaveAssets(); } if (OverlayType == "Eyes") { GUI.color = Green; } else { GUI.color = Color.gray; } if (GUILayout.Button("Eyes", GUILayout.ExpandWidth(true))) { OverlayType = "Eyes"; DK_Race _DK_Race = SelectedAnaPart.gameObject.GetComponent <DK_Race>(); _DK_Race.OverlayType = "Eyes"; EditorUtility.SetDirty(SelectedAnaPart.gameObject); AssetDatabase.SaveAssets(); } if (OverlayType == "Hair") { GUI.color = Green; } else { GUI.color = Color.gray; } if (GUILayout.Button("Hair", GUILayout.ExpandWidth(true))) { OverlayType = "Hair"; DK_Race _DK_Race = SelectedAnaPart.gameObject.GetComponent <DK_Race>(); _DK_Race.OverlayType = "Hair"; EditorUtility.SetDirty(SelectedAnaPart.gameObject); AssetDatabase.SaveAssets(); } } } // List GUI.color = Color.yellow; if (Helper) { GUILayout.TextField("Select an Anatomy Part from the following list. The 'P' letter is about Prefab, gray means that the Anatomy has no Prefab, cyan means that it is ok. Click on a gray 'P' to create a prefab.", 256, style, GUILayout.ExpandWidth(true), GUILayout.ExpandWidth(true)); } using (new Horizontal()) { GUI.color = Color.white; if (GUILayout.Button("Add New", GUILayout.ExpandWidth(true))) { GameObject NewExpressionObj = (GameObject)Instantiate(Resources.Load("New_AnatomyPart"), Vector3.zero, Quaternion.identity); NewExpressionObj.name = "New Anatomy Part (Rename)"; Selection.activeGameObject = NewExpressionObj; PrefabUtility.CreatePrefab("Assets/DK Editors/DK_UMA_Editor/Prefabs/DK_SlotsAnatomy/" + NewExpressionObj.name + ".prefab", NewExpressionObj.gameObject); if (_SlotsAnatomyLibrary) { DestroyImmediate(_SlotsAnatomyLibrary.gameObject); } SlotsAnatomyLibraryObj = (GameObject)Instantiate(Resources.Load("DK_SlotsAnatomyLibrary"), Vector3.zero, Quaternion.identity); SlotsAnatomyLibraryObj.name = "DK_SlotsAnatomyLibrary"; _SlotsAnatomyLibrary = SlotsAnatomyLibraryObj.GetComponent <DK_SlotsAnatomyLibrary>(); DK_UMA = GameObject.Find("DK_UMA"); if (DK_UMA == null) { var goDK_UMA = new GameObject(); goDK_UMA.name = "DK_UMA"; DK_UMA = GameObject.Find("DK_UMA"); } SlotsAnatomyLibraryObj.transform.parent = DK_UMA.transform; // Find prefabs DirectoryInfo dir = new DirectoryInfo("Assets/DK Editors/DK_UMA_Editor/Prefabs/DK_SlotsAnatomy"); // Assign Prefabs FileInfo[] info = dir.GetFiles("*.prefab"); info.Select(f => f.FullName).ToArray(); // Action // Verify Folders objects GameObject SlotsAnatomy = GameObject.Find("Slots Anatomy"); if (DK_UMA == null) { var goDK_UMA = new GameObject(); goDK_UMA.name = "DK_UMA"; var goSlotsAnatomy = new GameObject(); goSlotsAnatomy.name = "Slots Anatomy"; goSlotsAnatomy.transform.parent = goDK_UMA.transform; } else if (SlotsAnatomy == null) { SlotsAnatomy = new GameObject(); SlotsAnatomy.name = "Slots Anatomy"; SlotsAnatomy.transform.parent = DK_UMA.transform; } SlotsAnatomy = GameObject.Find("Slots Anatomy"); foreach (FileInfo f in info) { // Instantiate the Element Prefab GameObject clone = PrefabUtility.InstantiateAttachedAsset(Resources.LoadAssetAtPath("Assets/DK Editors/DK_UMA_Editor/Prefabs/DK_SlotsAnatomy/" + f.Name, typeof(GameObject))) as GameObject; clone.name = f.Name; if (clone.name.Contains(".prefab")) { clone.name = clone.name.Replace(".prefab", ""); } foreach (Transform child in SlotsAnatomy.transform) { if (clone != null && clone.name == child.name) { GameObject.DestroyImmediate(clone); } } if (clone != null) { clone.transform.parent = SlotsAnatomy.transform; // add the Element to the List DK_SlotsAnatomyElement _SlotsAnatomyElement = clone.GetComponent <DK_SlotsAnatomyElement>(); _SlotsAnatomyElement.dk_SlotsAnatomyElement.dk_SlotsAnatomyName = clone.name; if (_SlotsAnatomyElement.dk_SlotsAnatomyElement.ElemAlreadyIn == false) { for (int i = 0; i < _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList.Length; i++) { if (_SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i].dk_SlotsAnatomyElement != null && _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i].dk_SlotsAnatomyElement.ElemAlreadyIn == true) { } } if (_SlotsAnatomyElement.dk_SlotsAnatomyElement.ElemAlreadyIn == false) { var list = new DK_SlotsAnatomyElement[_SlotsAnatomyLibrary.dk_SlotsAnatomyElementList.Length + 1]; Array.Copy(_SlotsAnatomyLibrary.dk_SlotsAnatomyElementList, list, _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList.Length); GameObject _Prefab = PrefabUtility.GetPrefabParent(_SlotsAnatomyElement.gameObject) as GameObject; DK_SlotsAnatomyElement dk_SlotsAnatomyElement = _Prefab.GetComponent <DK_SlotsAnatomyElement>(); // add to list list[_SlotsAnatomyLibrary.dk_SlotsAnatomyElementList.Length] = dk_SlotsAnatomyElement; _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList = list; // modify dk_SlotsAnatomyName if necessary if (dk_SlotsAnatomyElement.dk_SlotsAnatomyElement.dk_SlotsAnatomyName == "") { dk_SlotsAnatomyElement.dk_SlotsAnatomyElement.dk_SlotsAnatomyName = dk_SlotsAnatomyElement.transform.name; } // Add to Dictonary if (!ElemAlreadyIn) { _SlotsAnatomyLibrary.dk_SlotsAnatomyDictionary.Add(_SlotsAnatomyElement.dk_SlotsAnatomyElement.dk_SlotsAnatomyName, dk_SlotsAnatomyElement.dk_SlotsAnatomyElement); dk_SlotsAnatomyElement.dk_SlotsAnatomyElement.ElemAlreadyIn = false; } } } } } DestroyImmediate(SlotsAnatomy); DestroyImmediate(NewExpressionObj); } // Copy if (GUILayout.Button("Copy Selected", GUILayout.ExpandWidth(true))) { string Path = "Assets/DK Editors/DK_UMA_Editor/Prefabs/DK_SlotsAnatomy/"; SelectedAnaPart.dk_SlotsAnatomyElement.dk_SlotsAnatomyName = SelectedAnaPart.name + " (Copy)"; AssetDatabase.CopyAsset(Path + SelectedAnaPart.gameObject.name + ".prefab", Path + SelectedAnaPart.gameObject.name + " (Copy).prefab"); SelectedAnaPart.dk_SlotsAnatomyElement.dk_SlotsAnatomyName = SelectedAnaPart.dk_SlotsAnatomyElement.dk_SlotsAnatomyName.Replace(" (Copy)", ""); AssetDatabase.Refresh(); if (_SlotsAnatomyLibrary) { DestroyImmediate(_SlotsAnatomyLibrary.gameObject); } SlotsAnatomyLibraryObj = (GameObject)Instantiate(Resources.Load("DK_SlotsAnatomyLibrary"), Vector3.zero, Quaternion.identity); SlotsAnatomyLibraryObj.name = "DK_SlotsAnatomyLibrary"; _SlotsAnatomyLibrary = SlotsAnatomyLibraryObj.GetComponent <DK_SlotsAnatomyLibrary>(); DK_UMA = GameObject.Find("DK_UMA"); if (DK_UMA == null) { var goDK_UMA = new GameObject(); goDK_UMA.name = "DK_UMA"; DK_UMA = GameObject.Find("DK_UMA"); } SlotsAnatomyLibraryObj.transform.parent = DK_UMA.transform; // Find prefabs DirectoryInfo dir = new DirectoryInfo("Assets/DK Editors/DK_UMA_Editor/Prefabs/DK_SlotsAnatomy"); // Assign Prefabs FileInfo[] info = dir.GetFiles("*.prefab"); info.Select(f => f.FullName).ToArray(); // Action // Verify Folders objects GameObject SlotsAnatomy = GameObject.Find("Slots Anatomy"); if (DK_UMA == null) { var goDK_UMA = new GameObject(); goDK_UMA.name = "DK_UMA"; var goSlotsAnatomy = new GameObject(); goSlotsAnatomy.name = "Slots Anatomy"; goSlotsAnatomy.transform.parent = goDK_UMA.transform; } else if (SlotsAnatomy == null) { SlotsAnatomy = new GameObject(); SlotsAnatomy.name = "Slots Anatomy"; SlotsAnatomy.transform.parent = DK_UMA.transform; } SlotsAnatomy = GameObject.Find("Slots Anatomy"); foreach (FileInfo f in info) { // Instantiate the Element Prefab GameObject clone = PrefabUtility.InstantiateAttachedAsset(Resources.LoadAssetAtPath("Assets/DK Editors/DK_UMA_Editor/Prefabs/DK_SlotsAnatomy/" + f.Name, typeof(GameObject))) as GameObject; clone.name = f.Name; if (clone.name.Contains(".prefab")) { clone.name = clone.name.Replace(".prefab", ""); } foreach (Transform child in SlotsAnatomy.transform) { if (clone != null && clone.name == child.name) { GameObject.DestroyImmediate(clone); } } if (clone != null) { clone.transform.parent = SlotsAnatomy.transform; // add the Element to the List DK_SlotsAnatomyElement _SlotsAnatomyElement = clone.GetComponent <DK_SlotsAnatomyElement>(); _SlotsAnatomyElement.dk_SlotsAnatomyElement.dk_SlotsAnatomyName = clone.name; if (_SlotsAnatomyElement.dk_SlotsAnatomyElement.ElemAlreadyIn == false) { for (int i = 0; i < _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList.Length; i++) { if (_SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i].dk_SlotsAnatomyElement != null && _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i].dk_SlotsAnatomyElement.ElemAlreadyIn == true) { } } if (_SlotsAnatomyElement.dk_SlotsAnatomyElement.ElemAlreadyIn == false) { var list = new DK_SlotsAnatomyElement[_SlotsAnatomyLibrary.dk_SlotsAnatomyElementList.Length + 1]; Array.Copy(_SlotsAnatomyLibrary.dk_SlotsAnatomyElementList, list, _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList.Length); GameObject _Prefab = PrefabUtility.GetPrefabParent(_SlotsAnatomyElement.gameObject) as GameObject; DK_SlotsAnatomyElement dk_SlotsAnatomyElement = _Prefab.GetComponent <DK_SlotsAnatomyElement>(); // add to list list[_SlotsAnatomyLibrary.dk_SlotsAnatomyElementList.Length] = dk_SlotsAnatomyElement; _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList = list; // modify dk_SlotsAnatomyName if necessary if (dk_SlotsAnatomyElement.dk_SlotsAnatomyElement.dk_SlotsAnatomyName == "") { dk_SlotsAnatomyElement.dk_SlotsAnatomyElement.dk_SlotsAnatomyName = dk_SlotsAnatomyElement.transform.name; } // Add to Dictonary if (!ElemAlreadyIn) { _SlotsAnatomyLibrary.dk_SlotsAnatomyDictionary.Add(_SlotsAnatomyElement.dk_SlotsAnatomyElement.dk_SlotsAnatomyName, dk_SlotsAnatomyElement.dk_SlotsAnatomyElement); dk_SlotsAnatomyElement.dk_SlotsAnatomyElement.ElemAlreadyIn = false; } } } } } DestroyImmediate(SlotsAnatomy); } // Delete GUI.color = Red; if (GUILayout.Button("Delete Selected", GUILayout.ExpandWidth(true))) { AssetDatabase.DeleteAsset("Assets/DK Editors/DK_UMA_Editor/Prefabs/DK_SlotsAnatomy/" + SelectedAnaPart.gameObject.name + ".prefab"); AssetDatabase.Refresh(); if (_SlotsAnatomyLibrary) { DestroyImmediate(_SlotsAnatomyLibrary.gameObject); } SlotsAnatomyLibraryObj = (GameObject)Instantiate(Resources.Load("DK_SlotsAnatomyLibrary"), Vector3.zero, Quaternion.identity); SlotsAnatomyLibraryObj.name = "DK_SlotsAnatomyLibrary"; _SlotsAnatomyLibrary = SlotsAnatomyLibraryObj.GetComponent <DK_SlotsAnatomyLibrary>(); DK_UMA = GameObject.Find("DK_UMA"); if (DK_UMA == null) { var goDK_UMA = new GameObject(); goDK_UMA.name = "DK_UMA"; DK_UMA = GameObject.Find("DK_UMA"); } SlotsAnatomyLibraryObj.transform.parent = DK_UMA.transform; // Find prefabs DirectoryInfo dir = new DirectoryInfo("Assets/DK Editors/DK_UMA_Editor/Prefabs/DK_SlotsAnatomy"); // Assign Prefabs FileInfo[] info = dir.GetFiles("*.prefab"); info.Select(f => f.FullName).ToArray(); // Action // Verify Folders objects GameObject SlotsAnatomy = GameObject.Find("Slots Anatomy"); if (DK_UMA == null) { var goDK_UMA = new GameObject(); goDK_UMA.name = "DK_UMA"; var goSlotsAnatomy = new GameObject(); goSlotsAnatomy.name = "Slots Anatomy"; goSlotsAnatomy.transform.parent = goDK_UMA.transform; } else if (SlotsAnatomy == null) { SlotsAnatomy = new GameObject(); SlotsAnatomy.name = "Slots Anatomy"; SlotsAnatomy.transform.parent = DK_UMA.transform; } SlotsAnatomy = GameObject.Find("Slots Anatomy"); foreach (FileInfo f in info) { // Instantiate the Element Prefab GameObject clone = PrefabUtility.InstantiateAttachedAsset(Resources.LoadAssetAtPath("Assets/DK Editors/DK_UMA_Editor/Prefabs/DK_SlotsAnatomy/" + f.Name, typeof(GameObject))) as GameObject; clone.name = f.Name; if (clone.name.Contains(".prefab")) { clone.name = clone.name.Replace(".prefab", ""); } foreach (Transform child in SlotsAnatomy.transform) { if (clone != null && clone.name == child.name) { GameObject.DestroyImmediate(clone); } } if (clone != null) { clone.transform.parent = SlotsAnatomy.transform; // add the Element to the List DK_SlotsAnatomyElement _SlotsAnatomyElement = clone.GetComponent <DK_SlotsAnatomyElement>(); _SlotsAnatomyElement.dk_SlotsAnatomyElement.dk_SlotsAnatomyName = clone.name; if (_SlotsAnatomyElement.dk_SlotsAnatomyElement.ElemAlreadyIn == false) { for (int i = 0; i < _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList.Length; i++) { if (_SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i].dk_SlotsAnatomyElement != null && _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i].dk_SlotsAnatomyElement.ElemAlreadyIn == true) { } } if (_SlotsAnatomyElement.dk_SlotsAnatomyElement.ElemAlreadyIn == false) { var list = new DK_SlotsAnatomyElement[_SlotsAnatomyLibrary.dk_SlotsAnatomyElementList.Length + 1]; Array.Copy(_SlotsAnatomyLibrary.dk_SlotsAnatomyElementList, list, _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList.Length); GameObject _Prefab = PrefabUtility.GetPrefabParent(_SlotsAnatomyElement.gameObject) as GameObject; DK_SlotsAnatomyElement dk_SlotsAnatomyElement = _Prefab.GetComponent <DK_SlotsAnatomyElement>(); // add to list list[_SlotsAnatomyLibrary.dk_SlotsAnatomyElementList.Length] = dk_SlotsAnatomyElement; _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList = list; // modify dk_SlotsAnatomyName if necessary if (dk_SlotsAnatomyElement.dk_SlotsAnatomyElement.dk_SlotsAnatomyName == "") { dk_SlotsAnatomyElement.dk_SlotsAnatomyElement.dk_SlotsAnatomyName = dk_SlotsAnatomyElement.transform.name; } // Add to Dictonary if (!ElemAlreadyIn) { _SlotsAnatomyLibrary.dk_SlotsAnatomyDictionary.Add(_SlotsAnatomyElement.dk_SlotsAnatomyElement.dk_SlotsAnatomyName, dk_SlotsAnatomyElement.dk_SlotsAnatomyElement); dk_SlotsAnatomyElement.dk_SlotsAnatomyElement.ElemAlreadyIn = false; } } } } } DestroyImmediate(SlotsAnatomy); } } #region Search using (new Horizontal()) { GUI.color = Color.white; GUILayout.Label("Search for :", GUILayout.ExpandWidth(false)); SearchString = GUILayout.TextField(SearchString, 100, GUILayout.ExpandWidth(true)); } #endregion Search GUILayout.Space(5); using (new Horizontal()) { GUI.color = Color.cyan; GUILayout.Label("Anatomy Part", "toolbarbutton", GUILayout.Width(112)); GUILayout.Label("Race", "toolbarbutton", GUILayout.Width(50)); GUILayout.Label("Gender", "toolbarbutton", GUILayout.Width(50)); GUILayout.Label("Type", "toolbarbutton", GUILayout.Width(80)); GUILayout.Label("", "toolbarbutton", GUILayout.ExpandWidth(true)); } if (_SlotsAnatomyLibrary != null) { using (new ScrollView(ref scroll)) { for (int i = 0; i < _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList.Length; i++) { DK_SlotsAnatomyElement dk_SlotsAnatomyElement = _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i]; if (_SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i] != null) { _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i].dk_SlotsAnatomyElement.ElemAlreadyIn = false; _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i].dk_SlotsAnatomyElement.Selected = false; if ((SearchString == "" || _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i].name.ToLower().Contains(SearchString.ToLower())) && dk_SlotsAnatomyElement != null) { using (new Horizontal(GUILayout.Width(80))) { // Prefab Verification myPath = PrefabUtility.GetPrefabObject(dk_SlotsAnatomyElement.gameObject).ToString(); if (myPath == "null") { GUI.color = Color.gray; } else { GUI.color = Color.cyan; } if (GUILayout.Button("P", "toolbarbutton", GUILayout.ExpandWidth(false))) { // Create Prefab if (myPath == "null") { PrefabUtility.CreatePrefab("Assets/DK Editors/DK_UMA_Editor/Prefabs/DK_SlotsAnatomy/" + dk_SlotsAnatomyElement.name + ".prefab", dk_SlotsAnatomyElement.gameObject); GameObject clone = PrefabUtility.InstantiateAttachedAsset(Resources.LoadAssetAtPath("Assets/DK Editors/DK_UMA_Editor/Prefabs/DK_SlotsAnatomy/" + dk_SlotsAnatomyElement.name + ".prefab", typeof(GameObject))) as GameObject; clone.name = dk_SlotsAnatomyElement.name; clone.transform.parent = dk_SlotsAnatomyElement.transform.parent; DestroyImmediate(dk_SlotsAnatomyElement.gameObject); } } // Element if (SelectedAnaPart == _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i]) { GUI.color = Color.yellow; } else { GUI.color = Color.white; } if (ChooseLink && GUILayout.Button(_SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i].dk_SlotsAnatomyElement.dk_SlotsAnatomyName, "toolbarbutton", GUILayout.Width(95))) { SelectedAnaPart.dk_SlotsAnatomyElement.Place = _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i]; EditorUtility.SetDirty(SelectedAnaPart.gameObject); AssetDatabase.SaveAssets(); ChooseLink = false; } if (!ChooseLink && GUILayout.Button(_SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i].dk_SlotsAnatomyElement.dk_SlotsAnatomyName, "toolbarbutton", GUILayout.Width(95))) { SelectedAnaPart = _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i]; Selection.activeGameObject = SelectedAnaPart.gameObject; NewAnatomyName = _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i].dk_SlotsAnatomyElement.dk_SlotsAnatomyName; NewPresetGender = _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i].dk_SlotsAnatomyElement.ForGender; DK_Race = _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i].GetComponent("DK_Race") as DK_Race; OverlayType = DK_Race.OverlayType; _SpawnPerct = Selection.activeGameObject.GetComponent <DK_SlotsAnatomyData>().SpawnPerct.ToString(); if (DK_Race.Place != null) { SelectedPlace = DK_Race.Place.ToString(); } else { SelectedPlace = ""; } } // Race if (_SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i].gameObject.GetComponent <DK_Race>() as DK_Race == null) { _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i].gameObject.AddComponent <DK_Race>(); } DK_Race = _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i].GetComponent("DK_Race") as DK_Race; if (DK_Race.Race.Count == 0) { GUI.color = Red; } if (DK_Race.Race.Count == 0 && GUILayout.Button("No Race", "toolbarbutton", GUILayout.Width(50))) { } GUI.color = Green; if (DK_Race.Race.Count == 1 && GUILayout.Button(DK_Race.Race[0], "toolbarbutton", GUILayout.Width(50))) { } if (DK_Race.Race.Count > 1 && GUILayout.Button("Multi", "toolbarbutton", GUILayout.Width(50))) { } // Gender if (DK_Race.Gender == "") { GUI.color = Red; } if (DK_Race.Gender == "") { GUILayout.Label("N", "Button"); } GUI.color = Green; if (DK_Race.Gender != "" && DK_Race.Gender == "Female") { GUILayout.Label("Female", "toolbarbutton", GUILayout.Width(50)); } if (DK_Race.Gender != "" && DK_Race.Gender == "Male") { GUILayout.Label("Male", "toolbarbutton", GUILayout.Width(50)); } if (DK_Race.Gender != "" && DK_Race.Gender == "Both") { GUILayout.Label("Both", "toolbarbutton", GUILayout.Width(50)); } // OverlayType if (_SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i].gameObject.GetComponent <DK_Race>() as DK_Race == null) { _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i].gameObject.AddComponent <DK_Race>(); } DK_Race = _SlotsAnatomyLibrary.dk_SlotsAnatomyElementList[i].GetComponent("DK_Race") as DK_Race; if (DK_Race.OverlayType == "") { GUI.color = Color.gray; } if (DK_Race.OverlayType == "" && GUILayout.Button("No Type", "toolbarbutton", GUILayout.Width(80))) { } GUI.color = Green; if (DK_Race.OverlayType != "" && GUILayout.Button(DK_Race.OverlayType, "toolbarbutton", GUILayout.Width(80))) { } } } } } } } }
static void Example() { string ret; // Create Material material = new Material(Shader.Find("Specular")); AssetDatabase.CreateAsset(material, "Assets/MyMaterial.mat"); if (AssetDatabase.Contains(material)) { Debug.Log("Material asset created"); } // Rename ret = AssetDatabase.RenameAsset("Assets/MyMaterial.mat", "MyMaterialNew"); if (ret == "") { Debug.Log("Material asset renamed to MyMaterialNew"); } else { Debug.Log(ret); } // Create a Folder ret = AssetDatabase.CreateFolder("Assets", "NewFolder"); if (AssetDatabase.GUIDToAssetPath(ret) != "") { Debug.Log("Folder asset created"); } else { Debug.Log("Couldn't find the GUID for the path"); } // Move ret = AssetDatabase.MoveAsset(AssetDatabase.GetAssetPath(material), "Assets/NewFolder/MyMaterialNew.mat"); if (ret == "") { Debug.Log("Material asset moved to NewFolder/MyMaterialNew.mat"); } else { Debug.Log(ret); } // Copy if (AssetDatabase.CopyAsset(AssetDatabase.GetAssetPath(material), "Assets/MyMaterialNew.mat")) { Debug.Log("Material asset copied as Assets/MyMaterialNew.mat"); } else { Debug.Log("Couldn't copy the material"); } // Manually refresh the Database to inform of a change AssetDatabase.Refresh(); Material MaterialCopy = AssetDatabase.LoadAssetAtPath("Assets/MyMaterialNew.mat", typeof(Material)) as Material; // Move to Trash if (AssetDatabase.MoveAssetToTrash(AssetDatabase.GetAssetPath(MaterialCopy))) { Debug.Log("MaterialCopy asset moved to trash"); } // Delete if (AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(material))) { Debug.Log("Material asset deleted"); } if (AssetDatabase.DeleteAsset("Assets/NewFolder")) { Debug.Log("NewFolder deleted"); } // Refresh the AssetDatabase after all the changes AssetDatabase.Refresh(); }
private void SetupDefaultSettings(AbstractPluginManager manager, string fromPath, string toPath) { Scene scene = EditorSceneManager.GetActiveScene(); string sceneName = scene.name; if (!AssetDatabase.IsValidFolder(toPath + "/" + AssetDatabaseUtility.dataFolderName)) { AssetDatabase.CreateFolder(toPath, AssetDatabaseUtility.dataFolderName); } string pluginFolder = fromPath.Split('/').First(); string fullToPath = toPath + "/" + AssetDatabaseUtility.dataFolderName + "/" + pluginFolder; if (!AssetDatabase.IsValidFolder(fullToPath)) { AssetDatabase.CreateFolder(toPath + "/" + AssetDatabaseUtility.dataFolderName, pluginFolder); } try { string[] fileEntries = Directory.GetFiles(Application.dataPath + "/" + fromPath); foreach (string fileName in fileEntries) { string temp = fileName.Replace("\\", "/"); int index = temp.LastIndexOf("/"); string localPath = "Assets/" + fromPath; if (index > 0) { localPath += temp.Substring(index); } UnityEngine.Object original = AssetDatabase.LoadAssetAtPath(localPath, typeof(ScriptableObject)); if (original != null) { string filename = Path.GetFileName(localPath); filename = filename.Replace("_Default", "_" + sceneName); if (AssetDatabase.GetMainAssetTypeAtPath(fullToPath + "/" + filename) == null) { AssetDatabase.CopyAsset(localPath, fullToPath + "/" + filename); } } // if AbstractPluginProfile copy it into Profile AbstractPluginProfile profile = (AbstractPluginProfile)AssetDatabase.LoadAssetAtPath(localPath, typeof(AbstractPluginProfile)); if (profile != null) { string filename = Path.GetFileName(localPath); filename = filename.Replace("_Default", "_" + sceneName); AssetDatabase.CopyAsset(localPath, toPath + "/" + AssetDatabaseUtility.dataFolderName + "/" + filename); manager.Profile = profile; } } } catch (Exception e) { Debug.LogError("Unable to copy plugin default settings. Digital Painting expects to find the default settings in " + fromPath + " see following exception for more information", this); Debug.LogException(e); } }
static private void ConvertIt(GameObject orgGo) { var orgPlayableDirector = orgGo.GetComponent <PlayableDirector>() as PlayableDirector; Assert.IsTrue(orgPlayableDirector != null, "PlayableDirector component is not attached to this GameObject." + orgGo); if (orgPlayableDirector == null) { return; } var orgAsset = orgPlayableDirector.playableAsset; if (orgAsset == null) { return; } if (orgAsset.GetType() != typeof(TimelineAsset)) { return; } Assert.IsTrue(AssetDatabase.Contains(orgAsset)); orgList.Add(orgAsset); // store gameobjects var orgBindings = orgAsset.outputs; List <Object> goList = new List <Object>(); foreach (PlayableBinding binding in orgBindings) { Object tmpObject = orgPlayableDirector.GetGenericBinding(binding.sourceObject) as Object; goList.Add(tmpObject); } // create new asset. var path = AssetDatabase.GetAssetPath(orgAsset); var uniquePath = AssetDatabase.GenerateUniqueAssetPath(path); AssetDatabase.CopyAsset(path, uniquePath); AssetDatabase.Refresh(); newAsset = AssetDatabase.LoadAssetAtPath(uniquePath, typeof(Object)) as TimelineAsset; if (newAsset == null) { return; } // improtant: clear all bindings to avoid leaving garbage. orgPlayableDirector.playableAsset = newAsset; orgBindings = newAsset.outputs; foreach (PlayableBinding binding in orgBindings) { var source = binding.sourceObject; orgPlayableDirector.SetGenericBinding(source, null); } orgPlayableDirector.playableAsset = orgAsset; // done cleaning. var cloneGo = GameObject.Instantiate(orgGo); var parent = orgGo.transform.parent; cloneGo.transform.SetParent(parent); cloneGo.transform.SetSiblingIndex(parent == null ? 0 : parent.transform.childCount - 1); cloneGo.transform.localPosition = orgGo.transform.localPosition; cloneGo.transform.localRotation = orgGo.transform.localRotation; cloneGo.transform.localScale = orgGo.transform.localScale; cloneGo.name = orgGo.name; cloneGo.name = GameObjectUtility.GetUniqueNameForSibling(parent, cloneGo.name); newPlayableDirector = cloneGo.GetComponent <PlayableDirector>() as PlayableDirector; if (newPlayableDirector == null) { return; } newPlayableDirector.playableAsset = newAsset; var newBindings = newAsset.outputs; int index = 0; foreach (PlayableBinding binding in newBindings) { newPlayableDirector.SetGenericBinding(binding.sourceObject, goList[index++]); } // start to modify tracks in the new playable asset. var rootTracks = UpdateManager.GetTrackList(newAsset); ProcessTracks(null, rootTracks, goList, 0); newPlayableDirector = null; newAsset = null; Debug.Log("Done duplicate " + orgGo); }
void OnGUI() { if (Event.current.type == EventType.Layout) { if (newAssetPath != null) { GUIUtility.keyboardControl = 0; GUIUtility.hotControl = 0; assetsPaths = newAssetPath; newAssetPath = null; } if (assetsPaths.IndexOf('\\') >= 0) { assetsPaths = assetsPaths.Replace('\\', '/'); } //if (destinationFolder != null) // { string destpath = Application.dataPath + "/Resources"; // if (string.IsNullOrEmpty(destpath)) // { //destinationFolder = null; // } // else if (!System.IO.Directory.Exists(destpath)) // { // destpath = destpath.Substring(0, destpath.LastIndexOf('/')); // destinationFolder = AssetDatabase.LoadMainAssetAtPath(destpath); // } // } } GUILayout.BeginHorizontal("Toolbar"); GUILayout.Label(""); GUILayout.EndHorizontal(); // templateAsset = EditorGUILayout.ObjectField("Template Asset", templateAsset, typeof(Object), false); // destinationFolder = EditorGUILayout.ObjectField("Destination Folder", destinationFolder, typeof(Object), false); GUILayout.Label("Where to find picture on your computer"); GUILayout.Space(2); scrollPosition = GUILayout.BeginScrollView(scrollPosition); assetsPaths = GUILayout.TextArea(assetsPaths); GUILayout.Label("Pixel skip (positive integer -- 1-4 can lag alot"); str1 = GUILayout.TextArea(str1); int.TryParse(str1, out pixelSkip); GUILayout.Label("Block size (positive float)"); str2 = GUILayout.TextArea(str2); float.TryParse(str2, out cubeSize); GUILayout.Label("Player size (positive float >= 0.5)"); str3 = GUILayout.TextArea(str3); float.TryParse(str3, out playerSize); Event evt = Event.current; Rect drop_area = GUILayoutUtility.GetLastRect(); switch (evt.type) { case EventType.DragUpdated: case EventType.DragPerform: if (!drop_area.Contains(evt.mousePosition)) { return; } DragAndDrop.visualMode = DragAndDropVisualMode.Copy; if (evt.type == EventType.DragPerform) { DragAndDrop.AcceptDrag(); StringBuilder sb = new StringBuilder(); foreach (var path in assetsPaths.Split('\n', '\r')) { if (string.IsNullOrEmpty(path)) { continue; } sb.AppendFormat("{0}\n", path.ToString()); } foreach (var path in DragAndDrop.paths) { if (string.IsNullOrEmpty(path)) { continue; } sb.AppendFormat("{0}\n", path.ToString()); } newAssetPath = sb.ToString(); } break; } GUILayout.EndScrollView(); if (GUILayout.Button("Import")) { var start = System.DateTime.Now; string destpath; // if( destinationFolder != null ) // { destpath = Application.dataPath + "/Resources"; // } // else // { // destpath = AssetDatabase.GetAssetPath(templateAsset); // destpath = destpath.Substring(0,destpath.LastIndexOf('/')); // } List <Object> assets = new List <Object>(); string assetDest = ""; foreach (var assetPath in assetsPaths.Split('\n', '\r')) { if (string.IsNullOrEmpty(assetPath)) { continue; } assetDest = destpath + assetPath.Substring(assetPath.LastIndexOf('/')); //assetDest = AssetDatabase.GenerateUniqueAssetPath(assetDest); AssetDatabase.CopyAsset(assetPath, destpath); System.IO.File.Copy(assetPath, assetDest, true); //AssetDatabase.ImportAsset(assetDest); assets.Add(AssetDatabase.LoadAssetAtPath(assetDest, typeof(Texture2D))); } AssetDatabase.SaveAssets(); Selection.instanceIDs = new int[0]; Selection.objects = assets.ToArray(); AssetDatabase.Refresh(); string str = assetDest.Substring(assetDest.LastIndexOf('/') + 1); pic = (Texture2D)Resources.Load(str.Replace(".jpeg", "").Replace(".jpg", "").Replace(".png", "")) as Texture2D; BuildLevel(); } GUILayout.Space(6); if (GUILayout.Button("Reset")) { Application.LoadLevel(0); } }
public void GenerateInventory() { string generatedDirPath = $"Assets/Merlin/Inventory/_generated/{descriptorGUID}"; if (!Directory.Exists(generatedDirPath)) { Directory.CreateDirectory(generatedDirPath); } // Generate the stage parameters for the inventory toggles VRCExpressionParameters inventoryStageParams; string stageParameterPath = $"{generatedDirPath}/customStageParams.asset"; if (basisStageParameters != null) { AssetDatabase.CopyAsset(AssetDatabase.GetAssetPath(basisStageParameters), stageParameterPath); inventoryStageParams = AssetDatabase.LoadAssetAtPath <VRCExpressionParameters>(stageParameterPath); } else { inventoryStageParams = ScriptableObject.CreateInstance <VRCExpressionParameters>(); AssetDatabase.CreateAsset(inventoryStageParams, $"{generatedDirPath}/customStageParams.asset"); } List <VRCExpressionParameters.Parameter> originalParams = new List <VRCExpressionParameters.Parameter>(); if (inventoryStageParams.parameters != null) { foreach (VRCExpressionParameters.Parameter param in inventoryStageParams.parameters) { if (!string.IsNullOrEmpty(param.name)) { originalParams.Add(new VRCExpressionParameters.Parameter() { name = param.name, valueType = param.valueType }); } } } if (inventorySlots.Length + originalParams.Count > 16) { Debug.LogError($"Cannot have more than {16 - originalParams.Count} inventory slots"); return; } VRCExpressionParameters.Parameter[] basisParameters = inventoryStageParams.parameters; inventoryStageParams.parameters = new VRCExpressionParameters.Parameter[16]; for (int i = 0; i < originalParams.Count; ++i) { inventoryStageParams.parameters[i] = originalParams[i]; } for (int i = originalParams.Count; i < inventorySlots.Length + originalParams.Count; ++i) { inventoryStageParams.parameters[i] = new VRCExpressionParameters.Parameter() { name = $"GenInventorySlot{i - originalParams.Count}", valueType = VRCExpressionParameters.ValueType.Int } } ; for (int i = originalParams.Count + inventorySlots.Length; i < 16; ++i) // Clear out empty params { inventoryStageParams.parameters[i] = new VRCExpressionParameters.Parameter() { name = "", valueType = VRCExpressionParameters.ValueType.Float } } ; // Generate menu asset VRCExpressionsMenu menuAsset; string menuPath = $"{generatedDirPath}/expressionMenu.asset"; if (basisMenu) { AssetDatabase.CopyAsset(AssetDatabase.GetAssetPath(basisMenu), menuPath); menuAsset = AssetDatabase.LoadAssetAtPath <VRCExpressionsMenu>(menuPath); } else { menuAsset = ScriptableObject.CreateInstance <VRCExpressionsMenu>(); AssetDatabase.CreateAsset(menuAsset, menuPath); } for (int i = 0; i < inventorySlots.Length; ++i) { menuAsset.controls.Add(new VRCExpressionsMenu.Control() { icon = inventorySlots[i].slotIcon, name = inventorySlots[i].slotName, parameter = new VRCExpressionsMenu.Control.Parameter() { name = $"GenInventorySlot{i}" }, type = VRCExpressionsMenu.Control.ControlType.Toggle, value = 1, }); } // Generate controller AnimatorController controller; string controllerPath = $"{generatedDirPath}/inventoryController.controller"; if (basisAnimator) { AssetDatabase.CopyAsset(AssetDatabase.GetAssetPath(basisAnimator), controllerPath); controller = AssetDatabase.LoadAssetAtPath <AnimatorController>(controllerPath); } else { controller = AnimatorController.CreateAnimatorControllerAtPath(controllerPath); } AnimationClip[] inventoryClips = new AnimationClip[inventorySlots.Length]; // Generate layer mask AvatarMask maskEverything = new AvatarMask(); for (int i = 0; i < (int)AvatarMaskBodyPart.LastBodyPart; ++i) { maskEverything.SetHumanoidBodyPartActive((AvatarMaskBodyPart)i, false); } maskEverything.name = "maskEverythingMask"; AssetDatabase.AddObjectToAsset(maskEverything, controller); // Generate animation clips for (int i = 0; i < inventorySlots.Length; ++i) { InventorySlot slot = inventorySlots[i]; // Set initial object state foreach (GameObject toggleObject in slot.slotToggleItems) { if (toggleObject) { toggleObject.SetActive(slot.startEnabled); } } string animationClipPath = $"{generatedDirPath}/Animations/_toggle{i}.anim"; AnimationClip toggleClip = GenerateToggleClip(slot.slotToggleItems, !slot.startEnabled); //AssetDatabase.CreateAsset(toggleClip, animationClipPath); inventoryClips[i] = toggleClip; toggleClip.name = $"toggleAnim{i}"; AssetDatabase.AddObjectToAsset(toggleClip, controller); } // Generate controller layers for (int i = 0; i < inventorySlots.Length; ++i) { string paramName = $"GenInventorySlot{i}"; controller.AddParameter(paramName, AnimatorControllerParameterType.Int); string layerName = $"GenToggleLayer{i}"; AnimatorControllerLayer toggleLayer = new AnimatorControllerLayer(); toggleLayer.name = layerName; toggleLayer.defaultWeight = 1f; toggleLayer.stateMachine = new AnimatorStateMachine(); toggleLayer.stateMachine.name = toggleLayer.name; toggleLayer.stateMachine.hideFlags = HideFlags.HideInHierarchy; toggleLayer.avatarMask = maskEverything; if (AssetDatabase.GetAssetPath(controller) != "") { AssetDatabase.AddObjectToAsset(toggleLayer.stateMachine, AssetDatabase.GetAssetPath(controller)); } AnimatorStateMachine stateMachine = toggleLayer.stateMachine; AnimatorState nullState = stateMachine.AddState("Null State", stateMachine.entryPosition + new Vector3(200f, 0f)); AnimatorState toggleState = stateMachine.AddState("Toggle Triggered", stateMachine.entryPosition + new Vector3(500f, 0f)); toggleState.motion = inventoryClips[i]; AnimatorStateTransition toToggle = nullState.AddTransition(toggleState); toToggle.exitTime = 0f; toToggle.hasExitTime = false; toToggle.hasFixedDuration = true; toToggle.duration = 0f; AnimatorStateTransition toNull = toggleState.AddTransition(nullState); toNull.exitTime = 0f; toNull.hasExitTime = false; toNull.hasFixedDuration = true; toNull.duration = 0f; toToggle.AddCondition(AnimatorConditionMode.Greater, 0f, paramName); toNull.AddCondition(AnimatorConditionMode.Equals, 0f, paramName); controller.AddLayer(toggleLayer); } // Setup layers on the avatar descriptor VRCAvatarDescriptor descriptor = GetComponent <VRCAvatarDescriptor>(); descriptor.expressionsMenu = menuAsset; descriptor.expressionParameters = inventoryStageParams; VRCAvatarDescriptor.CustomAnimLayer layer = new VRCAvatarDescriptor.CustomAnimLayer(); layer.isDefault = false; layer.animatorController = controller; layer.type = inventoryAnimLayer; for (int i = 0; i < descriptor.baseAnimationLayers.Length; ++i) { if (descriptor.baseAnimationLayers[i].type == inventoryAnimLayer) { descriptor.baseAnimationLayers[i] = layer; break; } } AssetDatabase.SaveAssets(); }
static void MakeTextureCombo(string pathRGB, string suffixRGB, string suffixA, string suffixCombo) { string pathBase = pathRGB.Substring(0, pathRGB.LastIndexOf(suffixRGB)); string pathA = pathBase + suffixA; string pathCombo = pathBase + suffixCombo; Texture2D textureRGB = AssetDatabase.LoadAssetAtPath <Texture2D> (pathRGB); Texture2D textureA = AssetDatabase.LoadAssetAtPath <Texture2D> (pathA); Texture2D textureCombo = AssetDatabase.LoadAssetAtPath <Texture2D> (pathCombo); if (textureRGB != null && textureA != null) { if (textureCombo == null) { if (AssetDatabase.CopyAsset(pathRGB, pathCombo)) { AssetDatabase.Refresh(); textureCombo = AssetDatabase.LoadAssetAtPath <Texture2D> (pathCombo); Debug.Log("Creating " + pathCombo); } else { Debug.LogError("Failed to copy " + pathRGB); } } // Make them readable! TextureImporter tImporterRGB = AssetImporter.GetAtPath(pathRGB) as TextureImporter; tImporterRGB.textureType = TextureImporterType.Advanced; tImporterRGB.isReadable = true; AssetDatabase.ImportAsset(pathRGB); TextureImporter tImporterA = AssetImporter.GetAtPath(pathA) as TextureImporter; tImporterA.textureType = TextureImporterType.Advanced; tImporterA.isReadable = true; AssetDatabase.ImportAsset(pathA); TextureImporter tImporterCombo = AssetImporter.GetAtPath(pathCombo) as TextureImporter; tImporterCombo.textureType = TextureImporterType.Advanced; tImporterCombo.isReadable = true; tImporterCombo.textureFormat = TextureImporterFormat.RGBA32; // tImporterCombo.textureType = TextureImporterType. tImporterCombo.alphaIsTransparency = true; AssetDatabase.ImportAsset(pathCombo); AssetDatabase.Refresh(); // Copy over data. Color32[] dataRGB = textureRGB.GetPixels32(); Color32[] dataA = textureA.GetPixels32(); if (dataRGB.Length != dataA.Length) { Debug.LogWarning("Cannot combine textures of unequal size: " + pathRGB + " and " + pathA); return; } bool hasTransparency = false; Color32[] dataCombo = new Color32[dataRGB.Length]; for (int h = 0; h < dataCombo.Length; h++) { dataCombo [h] = new Color32( dataRGB [h].r, dataRGB [h].g, dataRGB [h].b, dataA [h].r); hasTransparency |= (dataA [h].r != 255); // Have transparency if A not always saturated. } // Set the data for the new texture. textureCombo.SetPixels32(dataCombo); textureCombo.alphaIsTransparency = true; textureCombo.Apply(); // Clean up texture import settings. tImporterRGB.isReadable = false; tImporterRGB.textureType = TextureImporterType.Image; AssetDatabase.ImportAsset(pathRGB); tImporterA.isReadable = false; tImporterA.textureType = TextureImporterType.Image; AssetDatabase.ImportAsset(pathA); File.WriteAllBytes(pathCombo, textureCombo.EncodeToPNG()); tImporterCombo.isReadable = false; tImporterCombo.textureType = TextureImporterType.Image; tImporterCombo.alphaIsTransparency = hasTransparency; tImporterCombo.textureFormat = TextureImporterFormat.AutomaticCompressed; AssetDatabase.ImportAsset(pathCombo); AssetDatabase.Refresh(); } else { Debug.Log("Found diffuse but no matching opacity: " + pathA); } }
private void Finish() { if (!references) { GetReferences(); } if (!references) { return; } string managerPath = gameName + "/Managers"; try { System.IO.Directory.CreateDirectory(Application.dataPath + "/" + managerPath); } catch { Debug.LogWarning("Could not create directory: " + Application.dataPath + "/" + managerPath); pageNumber--; return; } try { ScriptableObject t = CustomAssetUtility.CreateAsset <SceneManager> ("SceneManager", managerPath); AssetDatabase.RenameAsset("Assets/" + managerPath + "/SceneManager.asset", gameName + "_SceneManager"); references.sceneManager = (SceneManager)t; t = CustomAssetUtility.CreateAsset <SettingsManager> ("SettingsManager", managerPath); AssetDatabase.RenameAsset("Assets/" + managerPath + "/SettingsManager.asset", gameName + "_SettingsManager"); references.settingsManager = (SettingsManager)t; references.settingsManager.saveFileName = gameName; references.settingsManager.cameraPerspective = cameraPerspective; references.settingsManager.movementMethod = movementMethod; references.settingsManager.inputMethod = inputMethod; references.settingsManager.interactionMethod = interactionMethod; references.settingsManager.hotspotDetection = hotspotDetection; references.settingsManager.movingTurning = movingTurning; if (cameraPerspective == CameraPerspective.TwoPointFiveD) { references.settingsManager.forceAspectRatio = true; } t = CustomAssetUtility.CreateAsset <ActionsManager> ("ActionsManager", managerPath); AssetDatabase.RenameAsset("Assets/" + managerPath + "/ActionsManager.asset", gameName + "_ActionsManager"); references.actionsManager = (ActionsManager)t; AdventureCreator.RefreshActions(); ActionsManager demoActionsManager = AssetDatabase.LoadAssetAtPath("Assets/AdventureCreator/Demo/Managers/Demo_ActionsManager.asset", typeof(ActionsManager)) as ActionsManager; if (demoActionsManager != null) { references.actionsManager.defaultClass = demoActionsManager.defaultClass; } t = CustomAssetUtility.CreateAsset <VariablesManager> ("VariablesManager", managerPath); AssetDatabase.RenameAsset("Assets/" + managerPath + "/VariablesManager.asset", gameName + "_VariablesManager"); references.variablesManager = (VariablesManager)t; t = CustomAssetUtility.CreateAsset <InventoryManager> ("InventoryManager", managerPath); AssetDatabase.RenameAsset("Assets/" + managerPath + "/InventoryManager.asset", gameName + "_InventoryManager"); references.inventoryManager = (InventoryManager)t; t = CustomAssetUtility.CreateAsset <SpeechManager> ("SpeechManager", managerPath); AssetDatabase.RenameAsset("Assets/" + managerPath + "/SpeechManager.asset", gameName + "_SpeechManager"); references.speechManager = (SpeechManager)t; references.speechManager.ClearLanguages(); t = CustomAssetUtility.CreateAsset <CursorManager> ("CursorManager", managerPath); AssetDatabase.RenameAsset("Assets/" + managerPath + "/CursorManager.asset", gameName + "_CursorManager"); references.cursorManager = (CursorManager)t; t = CustomAssetUtility.CreateAsset <MenuManager> ("MenuManager", managerPath); AssetDatabase.RenameAsset("Assets/" + managerPath + "/MenuManager.asset", gameName + "_MenuManager"); references.menuManager = (MenuManager)t; if (wizardMenu != WizardMenu.Blank) { CursorManager demoCursorManager = AssetDatabase.LoadAssetAtPath("Assets/AdventureCreator/Demo/Managers/Demo_CursorManager.asset", typeof(CursorManager)) as CursorManager; if (demoCursorManager != null) { foreach (CursorIcon demoIcon in demoCursorManager.cursorIcons) { CursorIcon newIcon = new CursorIcon(); newIcon.Copy(demoIcon); references.cursorManager.cursorIcons.Add(newIcon); } } else { Debug.LogWarning("Cannot find Demo_CursorManager asset to copy from!"); } references.cursorManager.allowMainCursor = true; CursorIconBase pointerIcon = new CursorIconBase(); pointerIcon.Copy(demoCursorManager.pointerIcon); references.cursorManager.pointerIcon = pointerIcon; EditorUtility.SetDirty(references.cursorManager); MenuManager demoMenuManager = AssetDatabase.LoadAssetAtPath("Assets/AdventureCreator/Demo/Managers/Demo_MenuManager.asset", typeof(MenuManager)) as MenuManager; if (demoMenuManager != null) { references.menuManager.drawOutlines = demoMenuManager.drawOutlines; references.menuManager.drawInEditor = demoMenuManager.drawInEditor; references.menuManager.pauseTexture = demoMenuManager.pauseTexture; if (wizardMenu == WizardMenu.DefaultUnityUI) { System.IO.Directory.CreateDirectory(Application.dataPath + "/" + gameName + "/UI"); } foreach (Menu demoMenu in demoMenuManager.menus) { Menu newMenu = ScriptableObject.CreateInstance <Menu>(); newMenu.Copy(demoMenu); if (wizardMenu == WizardMenu.DefaultAC) { newMenu.menuSource = MenuSource.AdventureCreator; } else if (wizardMenu == WizardMenu.DefaultUnityUI) { newMenu.menuSource = MenuSource.UnityUiPrefab; if (demoMenu.canvas) { string oldCanvasPath = AssetDatabase.GetAssetPath(demoMenu.canvas); string newCanvasPath = "Assets/" + gameName + "/UI/" + demoMenu.canvas.name + ".prefab"; if (AssetDatabase.CopyAsset(oldCanvasPath, newCanvasPath)) { AssetDatabase.ImportAsset(newCanvasPath); newMenu.canvas = (Canvas)AssetDatabase.LoadAssetAtPath(newCanvasPath, typeof(Canvas)); } } } newMenu.hideFlags = HideFlags.HideInHierarchy; references.menuManager.menus.Add(newMenu); EditorUtility.SetDirty(references.menuManager); foreach (MenuElement newElement in newMenu.elements) { newElement.hideFlags = HideFlags.HideInHierarchy; AssetDatabase.AddObjectToAsset(newElement, references.menuManager); } AssetDatabase.AddObjectToAsset(newMenu, references.menuManager); } } else { Debug.LogWarning("Cannot find Demo_MenuManager asset to copy from!"); } } CreateManagerPackage(gameName); AssetDatabase.SaveAssets(); references.sceneManager.InitialiseObjects(); pageNumber = 0; } catch { Debug.LogWarning("Could not create Manager. Does the subdirectory " + Resource.managersDirectory + " exist?"); pageNumber--; } }
/// <summary> /// Takes a path to an .fbx file and attempts to "fix" it up. /// </summary> private static void FixFuseModelAtPath(string assetPath) { // Only operate on FBX files if (assetPath.IndexOf(".fbx") == -1) { return; } UpdateProgressBar("Managing prefab.", 0f); string assetPathRoot = assetPath.Substring(0, assetPath.LastIndexOf(".fbx")); // Find or create the prefab version. string assetPathPrefab = assetPathRoot + " Prefab.prefab"; GameObject prefabObj = AssetDatabase.LoadAssetAtPath <GameObject> (assetPathPrefab); if (prefabObj == null) { // Create and instance of the model, make a prefab out of it, then remove the instance. Yikes. Debug.Log("Creating prefab: " + assetPathPrefab); GameObject instanceObj = GameObject.Instantiate(AssetDatabase.LoadAssetAtPath <GameObject> (assetPath)); prefabObj = PrefabUtility.CreatePrefab(assetPathPrefab, instanceObj, ReplacePrefabOptions.Default); GameObject.DestroyImmediate(instanceObj); } string textureFolder = assetPathRoot + ".fbm"; if (!AssetDatabase.IsValidFolder(textureFolder)) { return; } List <string> textureAssets = new List <string> (); textureAssets.AddRange(AssetDatabase.FindAssets("", new string[] { textureFolder })); // Scan for diffuse textures. for (int i = 0; i < textureAssets.Count; i++) { UpdateProgressBar("Combining textures.", 0.1f + (float)i / textureAssets.Count * 0.75f); string pathRGB = AssetDatabase.GUIDToAssetPath(textureAssets [i]); if (pathRGB.EndsWith("Diffuse.png")) { MakeTextureCombo(pathRGB, "Diffuse.png", "Opacity.png", "DiffuseOpacity.png"); } if (pathRGB.EndsWith("Specular.png")) { MakeTextureCombo(pathRGB, "Specular.png", "Gloss.png", "SpecularGloss.png"); } } string materialFolder = assetPath.Substring(0, assetPath.LastIndexOf("/")) + "/Materials"; if (!AssetDatabase.IsValidFolder(materialFolder)) { return; } List <string> materialAssetsGUIDs = new List <string> (); List <string> materialAssetsPaths = new List <string> (); materialAssetsGUIDs.AddRange(AssetDatabase.FindAssets("", new string[] { materialFolder })); for (int i = 0; i < materialAssetsGUIDs.Count; i++) { materialAssetsPaths.Add(AssetDatabase.GUIDToAssetPath(materialAssetsGUIDs [i])); } // Scan once to ensure eyeball and eyelash materials exist for each body material. for (int i = 0; i < materialAssetsPaths.Count; i++) { UpdateProgressBar("Assuring material instances.", 0.75f + (float)i / materialAssetsPaths.Count * 0.05f); // Eyeballs and eyelashes are initially set up with either under the Body or Packed0 materials. int indEyeSuffix = materialAssetsPaths [i].LastIndexOf("_Body_Diffuse.mat"); if (indEyeSuffix == -1) { indEyeSuffix = materialAssetsPaths [i].LastIndexOf("_Packed0_Diffuse.mat"); } if (indEyeSuffix != -1) { string pathRoot = materialAssetsPaths [i].Substring(0, indEyeSuffix); string eyeballsPath = pathRoot + "_Eyeballs.mat"; string eyelashesPath = pathRoot + "_Eyelashes.mat"; // Create these extra materials if they don't exist. if (!materialAssetsPaths.Contains(eyeballsPath)) { if (AssetDatabase.CopyAsset(materialAssetsPaths [i], eyeballsPath)) { AssetDatabase.Refresh(); Debug.Log("Creating " + eyeballsPath); materialAssetsGUIDs.Add(AssetDatabase.AssetPathToGUID(eyeballsPath)); materialAssetsPaths.Add(eyeballsPath); } else { Debug.LogError("Failed to copy " + materialAssetsPaths [i]); } } if (!materialAssetsPaths.Contains(eyelashesPath)) { if (AssetDatabase.CopyAsset(materialAssetsPaths [i], eyelashesPath)) { AssetDatabase.Refresh(); Debug.Log("Creating " + eyelashesPath); materialAssetsGUIDs.Add(AssetDatabase.AssetPathToGUID(eyelashesPath)); materialAssetsPaths.Add(eyelashesPath); } else { Debug.LogError("Failed to copy " + materialAssetsPaths [i]); } } } // Also, for packed textures, we find hair under Packed1. int indHairSuffix = materialAssetsPaths [i].LastIndexOf("_Packed1_Diffuse.mat"); if (indHairSuffix != -1) { string pathRoot = materialAssetsPaths [i].Substring(0, indHairSuffix); string hairPath = pathRoot + "_Hair_Diffuse.mat"; // Create these extra materials if they don't exist. if (!materialAssetsPaths.Contains(hairPath)) { if (AssetDatabase.CopyAsset(materialAssetsPaths [i], hairPath)) { AssetDatabase.Refresh(); Debug.Log("Creating " + hairPath); materialAssetsGUIDs.Add(AssetDatabase.AssetPathToGUID(hairPath)); materialAssetsPaths.Add(hairPath); } else { Debug.LogError("Failed to copy " + materialAssetsPaths [i]); } } } } // Scan again and set up properties. for (int i = 0; i < materialAssetsGUIDs.Count; i++) { UpdateProgressBar("Configuring materials.", 0.8f + (float)i / materialAssetsGUIDs.Count * 0.1f); string materialPath = AssetDatabase.GUIDToAssetPath(materialAssetsGUIDs [i]); Material material = AssetDatabase.LoadAssetAtPath <Material> (materialPath); // Set shader type. if (material.name.EndsWith("_Eyeballs")) { material.shader = Shader.Find("Standard"); // Hard-coded values that seem "okay" for eyeballs... material.SetFloat("_Metallic", 0.02f); material.SetFloat("_Glossiness", 0.8f); } else { material.shader = Shader.Find("Standard (Specular setup)"); } Texture t = material.GetTexture("_MainTex"); string tPath = AssetDatabase.GetAssetPath(t); // Replace either assigned diffuse or diffuse/opacity. (Because maybe spec/gloss not set up yet?) int suffixInd = tPath.LastIndexOf("_Diffuse.png"); if (suffixInd == -1) { suffixInd = tPath.LastIndexOf("_DiffuseOpacity.png"); } if (suffixInd != -1) { string tPathRoot = tPath.Substring(0, suffixInd); Texture2D dO = AssetDatabase.LoadAssetAtPath <Texture2D> (tPathRoot + "_DiffuseOpacity.png"); Texture2D sG = AssetDatabase.LoadAssetAtPath <Texture2D> (tPathRoot + "_SpecularGloss.png"); if (dO != null) { material.SetTexture("_MainTex", dO); // Assume all opaque except hair and eyelashes. if (material.name.EndsWith("_Eyelashes") || material.name.EndsWith("_Hair_Diffuse") || material.name.EndsWith("_Eyewear_Diffuse") || material.name.EndsWith("_Mask_Diffuse")) { material.SetFloat("_Mode", 2); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 0); material.DisableKeyword("_ALPHATEST_ON"); material.EnableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = 3000; } else { material.SetFloat("_Mode", 0); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 1); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); } } if (sG != null) { material.SetTexture("_SpecGlossMap", sG); } } } // Finally, check that the renderers are assigned to the correct materials. SkinnedMeshRenderer[] mr = prefabObj.GetComponentsInChildren <SkinnedMeshRenderer> (); for (int i = 0; i < mr.Length; i++) { UpdateProgressBar("Setting materials to renderers.", 0.9f + (float)i / materialAssetsGUIDs.Count * 0.1f); if (mr [i].name == "default") { SetUpEyeballs(mr [i]); } else if (mr [i].name == "Eyelashes") { SetUpEyelashes(mr [i]); } else if (mr [i].name == "Hair") { SetUpHair(mr [i]); } } EditorUtility.ClearProgressBar(); }
void GenerateData(string path) { var parent = Directory.GetParent(path).FullName; parent = parent.Substring(Application.dataPath.Length - "Assets".Length); // full path -> unity path var fileName = Path.GetFileName(path); var rootFolderPath = AssetDatabase.GUIDToAssetPath( AssetDatabase.CreateFolder(parent, fileName) ); var materialFolderPath = AssetDatabase.GUIDToAssetPath( AssetDatabase.CreateFolder(rootFolderPath, "Materials") ); var shaderFolderPath = AssetDatabase.GUIDToAssetPath( AssetDatabase.CreateFolder(rootFolderPath, "Shaders") ); // shader var templateShaderPath = AssetDatabase.GetAssetPath(m_GeneratorSettings.TemplateShader); var templateShaderExt = Path.GetExtension(templateShaderPath); var newShaderPath = Path.Combine(shaderFolderPath, fileName) + templateShaderExt; AssetDatabase.CopyAsset(templateShaderPath, newShaderPath); var newShader = AssetDatabase.LoadAssetAtPath(newShaderPath, typeof(Shader)) as Shader; // material var newMaterialPath = Path.Combine(materialFolderPath, fileName) + ".mat"; var newMaterial = new Material(newShader); AssetDatabase.CreateAsset(newMaterial, newMaterialPath); // scene var templateScenePath = AssetDatabase.GetAssetPath(m_GeneratorSettings.TemplateScene); var newScenePath = Path.Combine(rootFolderPath, fileName) + ".unity"; AssetDatabase.CopyAsset(templateScenePath, newScenePath); var newScene = EditorSceneManager.OpenScene(newScenePath, OpenSceneMode.Additive); // bind Material to MeshRenderer var meshRenderer = newScene.GetRootGameObjects() .Select(go => go.GetComponent <MeshRenderer>()) .FirstOrDefault(mr => mr != null); if (meshRenderer != null) { meshRenderer.material = newMaterial; } // bind Material to SoundShader var soundShader = newScene.GetRootGameObjects() .Select(go => go.GetComponent <SoundShader>()) .FirstOrDefault(ss => ss != null); if (soundShader != null) { soundShader.SetMaterial(newMaterial); } // save EditorSceneManager.SaveScene(newScene); EditorSceneManager.CloseScene(newScene, true); // refresh AssetDatabase.Refresh(); EditorGUIUtility.PingObject(newShader); // open scene if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { EditorSceneManager.OpenScene(newScenePath); } }
public static AnimatorController MergeControllers(AnimatorController mainController, AnimatorController controllerToMerge, Dictionary <string, string> paramNameSwap = null, bool saveToNew = false) { if (mainController == null) { return(null); } _parametersNewName = paramNameSwap ?? new Dictionary <string, string>(); _assetPath = AssetDatabase.GetAssetPath(mainController); if (saveToNew) { Directory.CreateDirectory("Assets/VRLabs/GeneratedAssets"); /*f (!AssetDatabase.IsValidFolder(_standardNewAnimatorFolder.Substring(0, _standardNewAnimatorFolder.Length - 1))) * { * AssetDatabase.CreateFolder("Assets/VRLabs", "GeneratedAssets"); * }*/ string uniquePath = AssetDatabase.GenerateUniqueAssetPath(_standardNewAnimatorFolder + Path.GetFileName(_assetPath)); AssetDatabase.CopyAsset(_assetPath, uniquePath); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); _assetPath = uniquePath; mainController = AssetDatabase.LoadAssetAtPath <AnimatorController>(_assetPath); } if (controllerToMerge == null) { return(mainController); } foreach (var p in controllerToMerge.parameters) { var newP = new AnimatorControllerParameter { name = _parametersNewName.ContainsKey(p.name) ? _parametersNewName[p.name] : p.name, type = p.type, defaultBool = p.defaultBool, defaultFloat = p.defaultFloat, defaultInt = p.defaultInt }; if (mainController.parameters.Count(x => x.name.Equals(newP.name)) == 0) { mainController.AddParameter(newP); } } for (int i = 0; i < controllerToMerge.layers.Length; i++) { AnimatorControllerLayer newL = CloneLayer(controllerToMerge.layers[i], i == 0); newL.name = MakeLayerNameUnique(newL.name, mainController); mainController.AddLayer(newL); } EditorUtility.SetDirty(mainController); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); return(mainController); }