private void CreatePrefabFromSelected() { //get selections and return errors Transform[] selection = Selection.GetTransforms(SelectionMode.Editable | SelectionMode.ExcludePrefab); if (selection.Length == 0) { EditorUtility.DisplayDialog("No GameObjects have been selected!", "Please select one or more GameObjects with Combined Meshes.", ""); return; } List <GameObject> selectionmeshes = new List <GameObject>(); for (int i = 0; i < selection.Length; i++) { //get meshes filters in seletion MeshFilter[] temps = selection[i].GetComponentsInChildren <MeshFilter>(); for (int n = 0; n < temps.Length; n++) { selectionmeshes.Add(temps[n].gameObject); } } //return error if not meshfilters if (selectionmeshes.Count == 0) { EditorUtility.DisplayDialog("No GameObjects with Combined Meshes selected!", "Please select one or more GameObjects with Combined Meshes.", ""); return; } //create save location if does not exist // bool doesExists = System.IO.Directory.Exists(targetFolder); // if (!doesExists) // System.IO.Directory.CreateDirectory(targetFolder); //save assets for (int i = 0; i < selectionmeshes.Count; i++) { if (selectionmeshes[i] == null)//repeat objects { continue; } string name = selectionmeshes[i].name.Replace("(Clone)", ""); // Debug.Log("Trying to Convert " + name + " into Prefab"); //Need to check for exisitence of sharedmesh and then if it is saved already MeshFilter lemesh = selectionmeshes[i].GetComponent <MeshFilter>(); if (lemesh != null) { if (lemesh.sharedMesh.name != "Combined Mesh")//ensuring combined mesh { Debug.LogError(name + " does not contain a Combined Mesh " + lemesh.sharedMesh.name + " " + lemesh.name); continue; } else if (!AssetDatabase.Contains(lemesh.sharedMesh)) { AssetDatabase.CreateAsset(lemesh.sharedMesh, targetFolder + "/" + name + ".asset"); } } else { continue; } //save prefab or replace it PrefabUtility.CreatePrefab(targetFolder + "/" + name + ".prefab", selectionmeshes[i].gameObject); Transform parent_tr = selectionmeshes[i].transform.parent; Vector3 child_pos = selectionmeshes[i].transform.position; //delete old to replace with prefab DestroyImmediate(selectionmeshes[i]); GameObject prefab_go = PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath(targetFolder + "/" + name + ".prefab", typeof(GameObject))) as GameObject; //ensure prefab replacement in scene prefab_go.transform.parent = parent_tr; prefab_go.transform.position = child_pos; } AssetDatabase.Refresh(); Debug.Log("Combined Meshes located in " + targetFolder); }
protected override bool CreateMesh() { base.CreateMesh(); #region ProgressBar const float MaxProgressCount = 5f; float ProgressCount = 0; Action <string> DisplayProgressBar = (info) => { if (voxelData.voxels.Length > 10000) { EditorUtility.DisplayProgressBar("Create Mesh...", string.Format("{0} / {1}", ProgressCount, MaxProgressCount), (ProgressCount++ / MaxProgressCount)); } }; #endregion DisplayProgressBar(""); #region Material { if (voxelBase.materialData == null) { voxelBase.materialData = new List <MaterialData>(); } if (voxelBase.materialData.Count == 0) { voxelBase.materialData.Add(null); } for (int i = 0; i < voxelBase.materialData.Count; i++) { if (voxelBase.materialData[i] == null) { voxelBase.materialData[i] = new MaterialData(); } } #region Erase for (int i = 0; i < voxelBase.materialData.Count; i++) { List <IntVector3> removeList = new List <IntVector3>(); voxelBase.materialData[i].AllAction((pos) => { if (voxelData.VoxelTableContains(pos) < 0) { removeList.Add(pos); } }); for (int j = 0; j < removeList.Count; j++) { voxelBase.materialData[i].RemoveMaterial(removeList[j]); } } #endregion if (materials == null) { materials = new List <Material>(); } if (materials.Count < voxelBase.materialData.Count) { for (int i = materials.Count; i < voxelBase.materialData.Count; i++) { materials.Add(null); } } else if (materials.Count > voxelBase.materialData.Count) { materials.RemoveRange(voxelBase.materialData.Count, materials.Count - voxelBase.materialData.Count); } } voxelBase.CreateMaterialIndexTable(); #endregion CalcDataCreate(voxelData.voxels); faceAreaTable = CreateFaceArea(voxelData.voxels); DisplayProgressBar(""); { var atlasTextureTmp = atlasTexture; if (!CreateTexture(faceAreaTable, voxelData.palettes, ref atlasRectTable, ref atlasTextureTmp, ref atlasRects)) { EditorUtility.ClearProgressBar(); return(false); } atlasTexture = atlasTextureTmp; for (int i = 0; i < materials.Count; i++) { if (materials[i] == null) { materials[i] = new Material(Shader.Find("Standard")); } else if (!AssetDatabase.Contains(materials[i])) { var tmp = Material.Instantiate(materials[i]); tmp.name = materials[i].name; materials[i] = tmp; } if (!AssetDatabase.Contains(materials[i])) { AddObjectToPrefabAsset(materials[i], "mat", i); } } if (!AssetDatabase.Contains(atlasTexture)) { AddObjectToPrefabAsset(atlasTexture, "tex"); } } DisplayProgressBar(""); { mesh = CreateMeshOnly(mesh, faceAreaTable, atlasTexture, atlasRects, atlasRectTable, Vector3.zero, out voxelBase.materialIndexes); if (!AssetDatabase.Contains(mesh)) { AddObjectToPrefabAsset(mesh, "mesh"); } } DisplayProgressBar(""); if (voxelBase.generateLightmapUVs) { if (mesh.uv.Length > 0) { Unwrapping.GenerateSecondaryUVSet(mesh); } } DisplayProgressBar(""); SetRendererCompornent(); RefreshCheckerSave(); EditorUtility.ClearProgressBar(); return(true); }
/// <summary> /// Called as a coroutine by ImportFile() /// </summary> /// <param name="absolutePath"></param> /// <param name="parentObject"></param> /// TODO: refactor this method, it is too long. private IEnumerator ImportFileAsync(string absolutePath, Transform parentObject) { Loader loader = CreateLoader(absolutePath); if (loader == null) { yield break; } loader.buildOptions = buildOptions; Debug.Log("Loading: " + absolutePath); float startTotTime = Time.realtimeSinceStartup; float startTime = Time.realtimeSinceStartup; importPhase = ImportPhase.TextureImport; string dirName = Path.GetDirectoryName(absolutePath); string sourceBasePath = string.IsNullOrEmpty(dirName) ? "" : dirName; if (!sourceBasePath.EndsWith("/")) { sourceBasePath += "/"; } string newName = Path.GetFileNameWithoutExtension(absolutePath);//fileInfo.Name.Substring(0, fileInfo.Name.Length - 4); if (importAssets) { Debug.LogFormat("Importing assets from {0}...", absolutePath); importMessage = "Creating folders..."; FileInfo fileInfo = new FileInfo(absolutePath); string fileName = fileInfo.Name; if (!string.IsNullOrEmpty(importAssetPath)) { EditorUtil.CreateAssetFolder("Assets", importAssetPath); EditorUtil.CreateAssetFolder("Assets/" + importAssetPath, fileName); } else { EditorUtil.CreateAssetFolder("Assets", fileName); } string prefabRelPath = (!string.IsNullOrEmpty(importAssetPath)) ? importAssetPath + "/" + fileName : fileName; string prefabPath = "Assets/" + prefabRelPath; string prefabName = prefabPath + "/" + fileName.Replace('.', '_') + ".prefab"; string[] texturePaths = loader.ParseTexturePaths(absolutePath); EditorUtil.CreateAssetFolder(prefabPath, "Textures"); EditorUtil.CreateAssetFolder(prefabPath, "Materials"); string destBasePath = Application.dataPath + "/../" + prefabPath; foreach (string texPath in texturePaths) { string source = texPath; if (!Path.IsPathRooted(source)) { source = sourceBasePath + texPath; } FileInfo texFileInfo = new FileInfo(source); string dest = destBasePath + "/Textures/" + texFileInfo.Name; importMessage = "Copying texture " + source + "..."; File.Copy(source, dest, true); Debug.LogFormat("Texture {0} copied to {1}", source, dest); } AssetDatabase.Refresh(); AssetDatabase.StartAssetEditing(); foreach (string texPath in texturePaths) { FileInfo textFileInfo = new FileInfo(texPath); string texAssetPath = prefabPath + "/Textures/" + textFileInfo.Name; importMessage = "Importing texture " + texAssetPath + "..."; EditorUtil.SetTextureReadable(texAssetPath); } AssetDatabase.SaveAssets(); AssetDatabase.StopAssetEditing(); //File.Copy(basePath+mtlLibName, destBasePath+mtlLibName, true); //File.Copy(absolutePath, destBasePath+fileName, true); importMessage = "Updating assets..."; AssetDatabase.Refresh(); Debug.LogFormat("Texture files imported in {0} seconds", Time.realtimeSinceStartup - startTime); startTime = Time.realtimeSinceStartup; importMessage = "Loading OBJ file..."; importPhase = ImportPhase.ObjLoad; loader.altTexPath = prefabPath + "/Textures/"; loader.buildOptions = buildOptions; yield return(StartCoroutine(loader.Load(newName, absolutePath, parentObject))); importMessage = "Saving assets..."; AssetDatabase.SaveAssets(); importMessage = "Refreshing assets..."; AssetDatabase.Refresh(); Debug.LogFormat("OBJ files loaded in {0} seconds", Time.realtimeSinceStartup - startTime); startTime = Time.realtimeSinceStartup; GameObject loadedObj = Loader.GetModelByPath(absolutePath); importMessage = "Creating mesh assets..."; importPhase = ImportPhase.AssetBuild; // TODO: check if the prefab already exists MeshFilter[] meshFilters = loadedObj.GetComponentsInChildren <MeshFilter>(); foreach (var filter in meshFilters) { Mesh mesh = filter.sharedMesh; if (!AssetDatabase.Contains(mesh)) { EditorUtil.CreateAssetFolder(prefabPath, "Meshes"); AssetDatabase.CreateAsset(mesh, prefabPath + "/Meshes/" + mesh.name + ".asset"); } } importMessage = "Creating material assets..."; AssetDatabase.StartAssetEditing(); MeshRenderer[] meshRend = loadedObj.GetComponentsInChildren <MeshRenderer>(); foreach (var rend in meshRend) { Material mtl = rend.sharedMaterial; if (!AssetDatabase.Contains(mtl)) { string mtlAssetPath = prefabPath + "/Materials/" + mtl.name + ".mat"; AssetDatabase.CreateAsset(mtl, mtlAssetPath); } } importMessage = "Saving assets..."; AssetDatabase.SaveAssets(); AssetDatabase.StopAssetEditing(); importMessage = "Updating assets..."; AssetDatabase.Refresh(); importMessage = "Creating prefab..."; PrefabUtility.CreatePrefab(prefabName, loadedObj, ReplacePrefabOptions.ConnectToPrefab); //GameObject. objObject.GetComponent<OBJ>(); Debug.LogFormat("Assets created in {0} seconds", Time.realtimeSinceStartup - startTime); importPhase = ImportPhase.Done; } else { importPhase = ImportPhase.ObjLoad; yield return(StartCoroutine(loader.Load(newName, absolutePath, parentObject))); } Debug.LogFormat("OBJ files imported in {0} seconds", Time.realtimeSinceStartup - startTotTime); }
protected override void OnInspector() { DrawAlphaTex(); DrawDefault("DensityTex"); DrawDefault("Sharpness"); DrawDefault("Indestructible"); DrawDefault("Binary"); Separator(); BeginError(Any(t => t.SplitDepth < 0)); { DrawDefault("SplitDepth"); } EndError(); BeginError(Any(t => t.MinSplitPixels < 0)); { DrawDefault("MinSplitPixels"); } EndError(); if (Targets.Length == 1 && AssetDatabase.Contains(Target) == false) { Separator(); EditorGUI.BeginDisabledGroup(true); { EditorGUILayout.IntField("Solid Pixel Count", Target.SolidPixelCount); EditorGUILayout.IntField("Original Solid Pixel Count", Target.OriginalSolidPixelCount); EditorGUILayout.Slider("Solid Pixel Ratio", Target.SolidPixelRatio, 0.0f, 1.0f); } EditorGUI.EndDisabledGroup(); var spriteRenderer = Target.GetComponent <SpriteRenderer>(); if (spriteRenderer != null) { var material = spriteRenderer.sharedMaterial; if (material != null) { if (material.HasProperty("_AlphaTex") == false) { EditorGUILayout.HelpBox("Material does not have a _AlphaTex texture property. It is required for D2D_DestructibleSprite.", MessageType.Warning); } if (material.HasProperty("_AlphaScale") == false) { EditorGUILayout.HelpBox("Material does not have a _AlphaScale texture property. It is required for D2D_DestructibleSprite.", MessageType.Warning); } if (material.HasProperty("_AlphaOffset") == false) { EditorGUILayout.HelpBox("Material does not have a _AlphaOffset texture property. It is required for D2D_DestructibleSprite.", MessageType.Warning); } } } } }
public override void OnInspectorGUI() { // Draw default GUI for MonoBehaviours base.OnInspectorGUI(); //EditorGUIUtility.whiteTexture = Color.white; GameObject[] selectedObjects = Selection.gameObjects; // Only work for multiple selections. if (selectedObjects.Length <= 1) { return; } // Only work in hierarchy, not project folder else if (selectedObjects.Any(o => AssetDatabase.Contains(o))) { return; } // Determine which buttons should be active bool showCreate = CreatePrefabFromSelected.SelectedItemsValid(selectedObjects); bool showApplyRevert = ApplySelectedPrefabs.SelectedItemsValid(selectedObjects); string errorMsg = string.Empty; // Ensure children and parent objects arent selected if (selectedObjects.Any(o => CreatePrefabFromSelected.WasParentSelected(o, selectedObjects))) { errorMsg = "Can't select GameObjects from same tree."; } // Only work if at least 1 control is active else if (!showApplyRevert && !showCreate) { errorMsg = "Can't mix prefabs and GameObjects."; } // ---- // Draw the GUI // ---- float designDPI = 96f; float dpiScale = Screen.dpi / designDPI; // Create a custom label style based on the current skin GUIStyle labelStyle = new GUIStyle(GUI.skin.label); labelStyle.margin = new RectOffset(0, 5, 5, 2); labelStyle.padding = new RectOffset(-1, 0, 0, 3); labelStyle.stretchWidth = false; // Begin the formatted area. GUILayout.BeginVertical(labelStyle); GUILayout.BeginHorizontal(labelStyle); GUILayout.Label(new GUIContent("Multifab"), labelStyle); // Create a custom box style for error messages GUIStyle errorBoxStyle = new GUIStyle(EditorStyles.helpBox); errorBoxStyle.fontSize = 10; errorBoxStyle.fixedHeight = 16; errorBoxStyle.margin = new RectOffset(4, -10, 4, 4); errorBoxStyle.padding = new RectOffset(0, 0, 0, 3); errorBoxStyle.alignment = TextAnchor.MiddleCenter; errorBoxStyle.normal.textColor = labelStyle.normal.textColor; if (string.IsNullOrEmpty(errorMsg)) { // Create a new style for the buttons GUIStyle buttonStyle = new GUIStyle(GUI.skin.button); buttonStyle.stretchWidth = true; //buttonStyle.margin = new RectOffset(0, 0, 3, 3); //buttonStyle.padding = new RectOffset(0, 0, 2, 3); buttonStyle.fontSize = 10; GUI.enabled = showCreate; if (GUILayout.Button("Create", buttonStyle)) { multifabMessage = CreatePrefabFromSelected.CreatePrefab(); nextRefresh = 0; } GUILayout.Space(-5f); GUI.enabled = showApplyRevert; if (GUILayout.Button("Revert", buttonStyle)) { multifabMessage = ApplySelectedPrefabs.SearchPrefabConnections(ApplySelectedPrefabs.RevertToSelectedPrefabs, PrefabAction.Revert); nextRefresh = 0; } GUILayout.Space(-5f); if (GUILayout.Button("Apply", buttonStyle)) { multifabMessage = ApplySelectedPrefabs.SearchPrefabConnections(ApplySelectedPrefabs.ApplyToSelectedPrefabs, PrefabAction.Apply); nextRefresh = 0; } GUILayout.Space(-5f); } else { GUILayout.Box(errorMsg, errorBoxStyle); } // Ensure that the GUI state is enabled as we finish up. GUI.enabled = true; // End the formatted area. EditorGUILayout.EndHorizontal(); Repaint(); errorBoxStyle.margin = new RectOffset(0, 4, 4, 4); if (!string.IsNullOrEmpty(multifabMessage)) { if (nextRefresh == 0) { GUILayout.Box(multifabMessage, errorBoxStyle); nextRefresh = EditorApplication.timeSinceStartup + refreshTime; } else if (nextRefresh > EditorApplication.timeSinceStartup) { GUILayout.Box(multifabMessage, errorBoxStyle); } else { multifabMessage = ""; } } EditorGUILayout.EndVertical(); }
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); }
public override void OnInspectorGUI() { serializedObject.Update(); var rect = GUILayoutUtility.GetRect(Screen.width - 38, bannerHeight, GUI.skin.box); if (logo) { GUI.DrawTexture(rect, logo, ScaleMode.ScaleToFit); } if (!Application.isPlaying) { var expand = false; var collapse = false; foreach (SteamVR_Camera target in targets) { if (AssetDatabase.Contains(target)) { continue; } if (target.isExpanded) { collapse = true; } else { expand = true; } } if (expand) { GUILayout.BeginHorizontal(); if (GUILayout.Button("Expand")) { foreach (SteamVR_Camera target in targets) { if (AssetDatabase.Contains(target)) { continue; } if (!target.isExpanded) { target.Expand(); EditorUtility.SetDirty(target); } } } GUILayout.Space(18); GUILayout.EndHorizontal(); } if (collapse) { GUILayout.BeginHorizontal(); if (GUILayout.Button("Collapse")) { foreach (SteamVR_Camera target in targets) { if (AssetDatabase.Contains(target)) { continue; } if (target.isExpanded) { target.Collapse(); EditorUtility.SetDirty(target); } } } GUILayout.Space(18); GUILayout.EndHorizontal(); } } EditorGUILayout.PropertyField(script); EditorGUILayout.PropertyField(wireframe); serializedObject.ApplyModifiedProperties(); }
/// <summary> /// Process the TextureCombiner. /// Unity creates the Texture Asset at the "savePath", and returns the Texture object. /// </summary> /// <param name="savePath">The path to save the Texture Asset to, relative to the Project folder.</param> /// <returns></returns> public Texture2D Combine(string savePath) { int xMin = int.MaxValue; int yMin = int.MaxValue; if (m_rSource.width > 4 && m_rSource.width < xMin) { xMin = m_rSource.width; } if (m_gSource.width > 4 && m_gSource.width < xMin) { xMin = m_gSource.width; } if (m_bSource.width > 4 && m_bSource.width < xMin) { xMin = m_bSource.width; } if (m_aSource.width > 4 && m_aSource.width < xMin) { xMin = m_aSource.width; } if (xMin == int.MaxValue) { xMin = 4; } if (m_rSource.height > 4 && m_rSource.height < yMin) { yMin = m_rSource.height; } if (m_gSource.height > 4 && m_gSource.height < yMin) { yMin = m_gSource.height; } if (m_bSource.height > 4 && m_bSource.height < yMin) { yMin = m_bSource.height; } if (m_aSource.height > 4 && m_aSource.height < yMin) { yMin = m_aSource.height; } if (yMin == int.MaxValue) { yMin = 4; } Texture2D combined = new Texture2D(xMin, yMin, GraphicsFormat.R32G32B32A32_SFloat, TextureCreationFlags.MipChain); combined.hideFlags = HideFlags.DontUnloadUnusedAsset; Material combinerMaterial = new Material(Shader.Find("Hidden/SRP_Core/TextureCombiner")); combinerMaterial.hideFlags = HideFlags.DontUnloadUnusedAsset; combinerMaterial.SetTexture("_RSource", GetRawTexture(m_rSource)); combinerMaterial.SetTexture("_GSource", GetRawTexture(m_gSource)); combinerMaterial.SetTexture("_BSource", GetRawTexture(m_bSource)); combinerMaterial.SetTexture("_ASource", GetRawTexture(m_aSource)); combinerMaterial.SetFloat("_RChannel", m_rChanel); combinerMaterial.SetFloat("_GChannel", m_gChanel); combinerMaterial.SetFloat("_BChannel", m_bChanel); combinerMaterial.SetFloat("_AChannel", m_aChanel); combinerMaterial.SetVector("_RRemap", m_remapings[0]); combinerMaterial.SetVector("_GRemap", m_remapings[1]); combinerMaterial.SetVector("_BRemap", m_remapings[2]); combinerMaterial.SetVector("_ARemap", m_remapings[3]); RenderTexture combinedRT = new RenderTexture(xMin, yMin, 0, GraphicsFormat.R32G32B32A32_SFloat); Graphics.Blit(Texture2D.whiteTexture, combinedRT, combinerMaterial); // Readback the render texture RenderTexture previousActive = RenderTexture.active; RenderTexture.active = combinedRT; combined.ReadPixels(new Rect(0, 0, xMin, yMin), 0, 0, false); combined.Apply(); RenderTexture.active = previousActive; byte[] bytes = new byte[0]; if (savePath.EndsWith("png")) { bytes = ImageConversion.EncodeToPNG(combined); } if (savePath.EndsWith("exr")) { bytes = ImageConversion.EncodeToEXR(combined); } if (savePath.EndsWith("jpg")) { bytes = ImageConversion.EncodeToJPG(combined); } string systemPath = Path.Combine(Application.dataPath.Remove(Application.dataPath.Length - 6), savePath); File.WriteAllBytes(systemPath, bytes); Object.DestroyImmediate(combined); AssetDatabase.ImportAsset(savePath); TextureImporter combinedImporter = (TextureImporter)AssetImporter.GetAtPath(savePath); combinedImporter.sRGBTexture = false; combinedImporter.SaveAndReimport(); if (savePath.EndsWith("exr")) { // The options for the platform string are: "Standalone", "iPhone", "Android", "WebGL", "Windows Store Apps", "PSP2", "PS4", "XboxOne", "Nintendo 3DS", "WiiU", "tvOS". combinedImporter.SetPlatformTextureSettings(new TextureImporterPlatformSettings() { name = "Standalone", format = TextureImporterFormat.DXT5, overridden = true }); } combined = AssetDatabase.LoadAssetAtPath <Texture2D>(savePath); //cleanup "raw" textures foreach (KeyValuePair <Texture, Texture> prop in m_RawTextures) { if (prop.Key != prop.Value && AssetDatabase.Contains(prop.Value)) { AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(prop.Value)); } } Object.DestroyImmediate(combinerMaterial); m_RawTextures.Clear(); return(combined); }
public override void OnGUI() { memberValue = gui.Object(displayText, memberValue, memberType, !AssetDatabase.Contains(unityTarget)); }
public static void ProcessObject(Location currentLocation, Object inspectedUnityObject, Object target, EntryAddSettings addSettings, ProcessObjectReferenceHandler processReferenceCallback) { var onlyVisibleProperties = currentLocation != Location.ScriptAsset; var componentTraverseInfo = new SerializedObjectTraverseInfo(target, onlyVisibleProperties); string lastScriptPropertyName = null; CSTraverseTools.TraverseObjectProperties(componentTraverseInfo, (info, sp) => { if (currentLocation == Location.ScriptAsset) { if (sp.isArray) { if (sp.type == "string") { if (sp.propertyPath.IndexOf("m_DefaultReferences.Array.data[", StringComparison.OrdinalIgnoreCase) == 0) { if (sp.stringValue != null) { lastScriptPropertyName = sp.stringValue; // skipping first pair item of the m_DefaultReferences array item sp.Next(false); } } } } } if (sp.propertyType == SerializedPropertyType.ObjectReference && sp.objectReferenceValue != null) { string propertyName; if (lastScriptPropertyName != null) { propertyName = lastScriptPropertyName; lastScriptPropertyName = string.Empty; } else { propertyName = sp.propertyPath; } /*if (string.Equals(propertyName, "m_Script", StringComparison.OrdinalIgnoreCase)) * { * propertyName = "Script source"; * }*/ addSettings.propertyPath = propertyName; processReferenceCallback(inspectedUnityObject, sp.objectReferenceInstanceIDValue, addSettings); /* material instance handling */ var material = sp.objectReferenceValue as Material; if (material == null) { return; } if (currentLocation == Location.PrefabAssetGameObject) { if (AssetDatabase.GetAssetPath(material) != AssetDatabase.GetAssetPath(target)) { return; } if (AssetDatabase.IsSubAsset(material)) { return; } } else { if (AssetDatabase.Contains(material)) { return; } } addSettings.prefix = "[Material Instance]"; addSettings.suffix = "(Main Texture)"; var mainTextureInstanceId = 0; if (material.HasProperty(MainTextureShaderProperty)) { var mainTexture = material.mainTexture; mainTextureInstanceId = mainTexture != null ? mainTexture.GetInstanceID() : 0; } processReferenceCallback(inspectedUnityObject, mainTextureInstanceId, addSettings); addSettings.suffix = "(Shader)"; var shaderInstanceId = material.shader != null ? material.shader.GetInstanceID() : 0; processReferenceCallback(inspectedUnityObject, shaderInstanceId, addSettings); var materialSo = new SerializedObject(material); var texEnvs = materialSo.FindProperty("m_SavedProperties.m_TexEnvs.Array"); if (texEnvs != null) { for (var k = 0; k < texEnvs.arraySize; k++) { var arrayItem = texEnvs.GetArrayElementAtIndex(k); var fieldName = arrayItem.displayName; if (fieldName == MainTexturePropertyName) { continue; } var textureProperty = arrayItem.FindPropertyRelative("second.m_Texture"); if (textureProperty != null) { if (textureProperty.propertyType == SerializedPropertyType.ObjectReference) { addSettings.suffix = " (" + fieldName + ")"; processReferenceCallback(inspectedUnityObject, textureProperty.objectReferenceInstanceIDValue, addSettings); } } else { Debug.LogError(Maintainer.ConstructError("Can't get second.m_Texture from texEnvs at " + inspectedUnityObject.name)); } } } else { Debug.LogError(Maintainer.ConstructError("Can't get m_SavedProperties.m_TexEnvs.Array from material instance at " + inspectedUnityObject.name)); } } lastScriptPropertyName = null; }); }
/// <summary> /// Ends drawing a property tree, and handles management of undo, as well as marking scenes and drawn assets dirty. /// </summary> /// <param name="tree">The tree.</param> public static void EndDrawPropertyTree(PropertyTree tree) { tree.InvokeDelayedActions(); if (tree.UnitySerializedObject != null) { if (mPropertyFieldGetter != null) { var obj = tree.UnitySerializedObject; IntPtr ptr = mPropertyFieldGetter(ref obj); if (ptr == IntPtr.Zero) { // SerializedObject has been disposed, likely due to a scene change invoked from GUI code. // BAIL THE F**K OUT! :D Crashes will happen. return; } } if (tree.WillUndo) { tree.UnitySerializedObject.ApplyModifiedProperties(); } else { tree.UnitySerializedObject.ApplyModifiedPropertiesWithoutUndo(); } } bool appliedOdinChanges = false; if (tree.ApplyChanges()) { appliedOdinChanges = true; GUIHelper.RequestRepaint(); if (tree.TargetType.ImplementsOrInherits(typeof(UnityEngine.Object))) { var targets = tree.WeakTargets; for (int i = 0; i < targets.Count; i++) { var target = (UnityEngine.Object)targets[i]; if (AssetDatabase.Contains(target)) { EditorUtility.SetDirty(target); } else if (Application.isPlaying == false) { #if UNITY_5_3_OR_NEWER if (tree.TargetType.ImplementsOrInherits(typeof(Component))) { Component component = (Component)target; EditorUtility.SetDirty(target); UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(component.gameObject.scene); } else { // We can't find out where this thing is from // It is probably a "temporary" UnityObject created from a script somewhere // Just to be safe, mark it as dirty, and mark all scenes as dirty EditorUtility.SetDirty(target); UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } #else EditorApplication.MarkSceneDirty(); #endif } } } } // This is very important, as applying changes may cause more actions to be delayed tree.InvokeDelayedActions(); if (appliedOdinChanges) { tree.InvokeOnValidate(); } drawnInspectorDepthCount--; #if ODIN_TRIAL_VERSION if (drawnInspectorDepthCount == 0) { float height = OdinTrialVersionInfo.IsExpired ? 22 : 17; var rect = GUILayoutUtility.GetRect(16, height, GUILayoutOptions.ExpandWidth().Height(height)); var bgRect = rect; bgRect.xMin -= 20; bgRect.xMax += 20; bgRect.y += 2; SirenixEditorGUI.DrawBorders(bgRect, 0, 0, 1, 0, SirenixGUIStyles.LightBorderColor); rect.y += 2; if (OdinTrialVersionInfo.IsExpired) { EditorGUI.DrawRect(bgRect, Color.black); GUIHelper.PushContentColor(Color.red); GUI.Label(rect.AddY(3), "Odin Inspector Trial expired!", SirenixGUIStyles.Label); GUIHelper.PopContentColor(); var btnRect = rect.AlignRight(EditorStyles.miniButton.CalcSize(new GUIContent("Purchase Odin Inspector")).x); btnRect.yMin += 2; btnRect.yMax -= 2; GUIHelper.PushColor(Color.green); if (GUI.Button(btnRect, "Purchase Odin Inspector", EditorStyles.miniButton)) { UnityEditorInternal.AssetStore.Open("content/89041"); } GUIHelper.PopColor(); } else { GUI.Label(rect, "Odin Inspector Trial Version", SirenixGUIStyles.LeftAlignedGreyMiniLabel); GUI.Label(rect, "Expires " + OdinTrialVersionInfo.ExpirationDate.ToShortDateString(), EditorStyles.centeredGreyMiniLabel); GUI.Label(rect, OdinTrialVersionInfo.ExpirationDate.Subtract(System.DateTime.Now).TotalHours.ToString("F2") + " hours remaining.", SirenixGUIStyles.RightAlignedGreyMiniLabel); } } #endif }
public void OnLayerGUI(Layout layout, int num) { layout.margin += 5; layout.rightMargin += 5; Texture2D source = texArrDec.GetSource(num, isAlpha: false); Texture2D alpha = texArrDec.GetSource(num, isAlpha: true); Texture2D preview = texArrDec.GetPreview(num); //save warnings if (!AssetDatabase.Contains(texArrDec.texArr)) { layout.Par(28); layout.Label("Source objects could not be saved since texture array is not stored as an asset", rect: layout.Inset(), helpbox: true); layout.Par(5); } else { //source Texture2D newSrc = layout.Field(source, "Source", fieldSize: 0.6f); if (source != newSrc) { texArrDec.SetSource(newSrc, num, isAlpha: false); } //alpha Texture2D newAlf = layout.Field(alpha, "Alpha", fieldSize: 0.6f, disabled: source == null); if (alpha != newAlf) { texArrDec.SetSource(newAlf, num, isAlpha: true); } } //preview/extract layout.Par(5); layout.Par(); layout.Label("Extract", rect: layout.Inset(0.4f)); if (layout.Button("Save", rect: layout.Inset(0.6f))) { string savePath = EditorUtility.SaveFilePanel("Save Texture", "Assets", texArrDec.texArr.name + " layer " + num, "png"); if (savePath != null) { preview.SaveAsPNG(savePath); } } layout.Par(); layout.Inset(0.4f); if (layout.Button("Save Gamma", rect: layout.Inset(0.6f))) { string savePath = EditorUtility.SaveFilePanel("Save Texture", "Assets", texArrDec.texArr.name + " layer " + num, "png"); if (savePath != null) { preview.SaveAsPNG(savePath, linear: true); } } layout.Par(); layout.Inset(0.4f); if (layout.Button("Save as Normal Map", rect: layout.Inset(0.6f))) { string savePath = EditorUtility.SaveFilePanel("Save Texture", "Assets", texArrDec.texArr.name + " layer " + num, "png"); if (savePath != null) { preview.SaveAsPNG(savePath, normal: true); } } //layout.Par(5); //layout.Par(); //layout.Label("Preview", rect:layout.Inset(0.4f)); //if (layout.Button(layer.preview==null? "Generate" : "Refresh", rect:layout.Inset(0.6f))) // layer.preview = texArr.GetTexture(num); layout.Par(Mathf.Min(layout.field.width, preview.height)); //layout.Texture(texArrDec.GetPreview(num), layout.Inset(), ref previewMode); layout.Texture(texArrDec.texArr.GetTexture(num), layout.Inset(), ref previewMode); //srcLayers[num] = layer; layout.Par(5); layout.margin -= 5; layout.rightMargin -= 5; }
public static string BakeAtlas(GuiAtlas atlas, string fileName) { if (!AssetDatabase.Contains(atlas)) { return("Atlas should be saved as asset"); } if (string.IsNullOrEmpty(fileName)) { return("Sprite folder not selected"); } // cleanup. try { if (atlas.ColorTexture != null && AssetDatabase.Contains(atlas.ColorTexture)) { var t = atlas.ColorTexture; atlas.ColorTexture = null; AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(t)); } } catch { } try { if (atlas.AlphaTexture != null && AssetDatabase.Contains(atlas.AlphaTexture)) { var t = atlas.AlphaTexture; atlas.AlphaTexture = null; AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(t)); } } catch { } AssetDatabase.Refresh(); var sprites = new List <Texture2D> (); foreach (var spriteFileName in Directory.GetFiles(fileName, "*.png", SearchOption.TopDirectoryOnly)) { var spriteTex = new Texture2D(2, 2); spriteTex.LoadImage(File.ReadAllBytes(spriteFileName)); spriteTex.Apply(); spriteTex.name = Path.GetFileNameWithoutExtension(spriteFileName); sprites.Add(spriteTex); } var atlasTex = new Texture2D(2, 2, TextureFormat.ARGB32, false); atlasTex.hideFlags = HideFlags.HideAndDontSave; Rect[] rects; if (sprites.Count == 1) { // special case, one texture rects = new Rect[] { new Rect(0, 0, 1f, 1f) }; atlasTex.LoadImage(sprites[0].EncodeToPNG()); atlasTex.Apply(); } else { rects = atlasTex.PackTextures(sprites.ToArray(), 2, 2048); } var tex = new Texture2D(atlasTex.width, atlasTex.height, TextureFormat.RGB24, false); tex.hideFlags = HideFlags.HideAndDontSave; var srcColors = atlasTex.GetPixels32(); DestroyImmediate(atlasTex); atlasTex = null; var dstAlphas = new Color32[srcColors.Length]; Color32 c; for (int i = 0; i < srcColors.Length; i++) { c = srcColors[i]; dstAlphas[i] = new Color32(c.a, c.a, c.a, 255); } tex.SetPixels32(srcColors); var colorData = tex.EncodeToPNG(); tex.SetPixels32(dstAlphas); var alphaData = tex.EncodeToPNG(); DestroyImmediate(tex); tex = null; try { var srcAtlasPath = AssetDatabase.GetAssetPath(atlas); EditorUtility.DisplayProgressBar("Save and import atlas data", "Color data processing...", 1f); var atlasPath = Path.ChangeExtension(srcAtlasPath, "color.png"); File.WriteAllBytes(Path.Combine(Path.Combine(Application.dataPath, ".."), atlasPath), colorData); EditorUtility.DisplayProgressBar("Save and import atlas data", "Alpha data processing...", 1f); var alphaAtlasPath = Path.ChangeExtension(srcAtlasPath, "alpha.png"); File.WriteAllBytes(Path.Combine(Path.Combine(Application.dataPath, ".."), alphaAtlasPath), alphaData); EditorUtility.DisplayProgressBar("Save and import atlas data", "Import processed data...", 1f); AssetDatabase.Refresh(); atlasTex = FixAtlasImport(atlasPath); atlas.ColorTexture = atlasTex; atlas.AlphaTexture = FixAtlasImport(alphaAtlasPath); var atlasSprites = new List <GuiSpriteData> (sprites.Count); float atlasWidth = atlasTex.width; float atlasHeight = atlasTex.height; for (int i = 0, iMax = sprites.Count; i < iMax; i++) { var sprData = new GuiSpriteData(); var sprName = sprites[i].name; // slicing var match = _slicedMask.Match(sprName.ToLowerInvariant()); if (match.Success) { sprName = sprName.Replace(match.Value, string.Empty); sprData.BorderL = int.Parse(match.Groups["left"].Value) / atlasWidth; sprData.BorderT = int.Parse(match.Groups["top"].Value) / atlasHeight; sprData.BorderR = int.Parse(match.Groups["right"].Value) / atlasWidth; sprData.BorderB = int.Parse(match.Groups["bottom"].Value) / atlasHeight; } else { sprData.BorderL = 0; sprData.BorderT = 0; sprData.BorderR = 0; sprData.BorderB = 0; } sprData.Name = sprName; sprData.CornerX = rects[i].x; sprData.CornerY = rects[i].y; sprData.CornerW = rects[i].width; sprData.CornerH = rects[i].height; atlasSprites.Add(sprData); } atlas.Sprites = atlasSprites.ToArray(); EditorUtility.SetDirty(atlas); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); atlas.ResetCache(); foreach (var panel in FindObjectsOfType <GuiPanel>()) { panel.ResetMaterialCache(); } foreach (var vis in FindObjectsOfType <GuiWidget>()) { vis.SetDirty(GuiDirtyType.Geometry); EditorUtility.SetDirty(vis); } } finally { EditorUtility.ClearProgressBar(); for (var i = sprites.Count - 1; i >= 0; i--) { DestroyImmediate(sprites[i]); sprites.RemoveAt(i); } } return(null); }
private void OnGUI() { windowScrollPos = EditorGUILayout.BeginScrollView(windowScrollPos, false, false); // if the window size is too small, add scroll bar Event e = Event.current; // draw title GUILayout.Label("Prefab Painter", Styles.titleStyle); GUILayout.Space(20); // buttons for choosing project template EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); is2D = GUILayout.Toggle(is2D, "2D Project", "button", GUILayout.Width(position.width / 3), GUILayout.Height(30)); GUILayout.FlexibleSpace(); is2D = !GUILayout.Toggle(!is2D, "3D Project", "button", GUILayout.Width(position.width / 3), GUILayout.Height(30)); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); GUILayout.Space(20); { // draw area to display all presets EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Presets", EditorStyles.boldLabel); if (GUILayout.Button("Delete")) { Settings.DeletePreset(); } EditorGUILayout.EndHorizontal(); // draw scroll field for displaying all the prefabs in the project int windowBorder = 2; Rect realRect = EditorGUILayout.GetControlRect(GUILayout.Height(Styles.presetIconHeight * Styles.presetWindowRows + windowBorder)); Rect virtualRect = new Rect(realRect); { virtualRect.width = Mathf.Max(virtualRect.width - 20, 1); // space for scroll int presetColumns = Mathf.FloorToInt(Mathf.Max(1, (virtualRect.width - windowBorder * 2) / Styles.presetIconWidth)); int virtualRows = Mathf.CeilToInt((float)Settings.allPresets.Count / presetColumns); virtualRect.height = Mathf.Max(virtualRect.height, Styles.presetIconHeight * virtualRows + windowBorder); } presetsScrollPos = GUI.BeginScrollView(realRect, presetsScrollPos, virtualRect, false, true); // Empty preset list - Drag&Drop Info if (Settings.allPresets.Count == 0) { GUIStyle labelStyle = new GUIStyle(EditorStyles.boldLabel) { fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleCenter }; EditorGUI.LabelField(realRect, "Drag & Drop Prefab Here", labelStyle); } int presetIndex = 0; int iconDrawCount = 0; int presetUnderCursor = -1; for (int y = (int)virtualRect.yMin + windowBorder; y < (int)virtualRect.yMax; y += Styles.presetIconHeight) { if (presetIndex >= Settings.allPresets.Count) { break; } for (int x = (int)virtualRect.xMin + windowBorder; (x + Styles.presetIconWidth) < (int)(virtualRect.xMax); x += Styles.presetIconWidth) { if (presetIndex >= Settings.allPresets.Count) { break; } Rect presetIconRectScrolled = new Rect(x - presetsScrollPos.x, y - presetsScrollPos.y, Styles.presetIconWidth, Styles.presetIconHeight); // only visible incons if (presetIconRectScrolled.Overlaps(realRect)) { Rect presetIconRect = new Rect(x, y, Styles.presetIconWidth, Styles.presetIconHeight); // detect the selected prefab if (presetIconRect.Contains(e.mousePosition)) { presetUnderCursor = presetIndex; } iconDrawCount++; // Draw all Prefab preview EditorGUI.DrawRect(new Rect(presetIconRect.x, presetIconRect.y, 0, 0), Styles.colorBlue); // detect selected preset if (presetUnderCursor == presetIndex) { if (e.type == EventType.MouseDown && e.button == 0) { Settings.selectedIndex = presetUnderCursor; presetName = Settings.GetSelectedName(); } else { EditorGUI.DrawRect(presetIconRect, Color.gray); } } if (Settings.selectedIndex == presetIndex) { EditorGUI.DrawRect(presetIconRect, Styles.colorBlue); } Rect iconRect = new Rect(x + 1, y + 1, Styles.presetIconWidth - 2, Styles.presetIconWidth - 2); // Prefab preview Texture2D presetPreview = AssetPreview.GetAssetPreview(Settings.allPresets[presetIndex]); if (presetPreview != null) { GUI.DrawTexture(iconRect, presetPreview); } else { // Missing prefab GUIStyle labelStyle = new GUIStyle(EditorStyles.boldLabel); labelStyle.normal.textColor = Color.red; labelStyle.alignment = TextAnchor.LowerCenter; EditorGUI.LabelField(presetIconRect, "Missing", labelStyle); labelStyle = new GUIStyle(EditorStyles.miniLabel) { alignment = TextAnchor.MiddleCenter }; EditorGUI.LabelField(iconRect, "Image not\navaiable", labelStyle); } } presetIndex++; } } // Drag & Drop if (e.type == EventType.DragUpdated || e.type == EventType.DragPerform) { DragAndDrop.visualMode = DragAndDropVisualMode.Copy; if (e.type == EventType.DragPerform) { DragAndDrop.AcceptDrag(); foreach (UnityEngine.Object draggedObject in DragAndDrop.objectReferences) { if (draggedObject is GameObject && PrefabUtility.GetPrefabType(draggedObject as GameObject) != PrefabType.None && AssetDatabase.Contains(draggedObject)) { if (!Settings.allPresets.Contains((GameObject)draggedObject)) { Settings.AddPreset(draggedObject as GameObject); } } } } e.Use(); Repaint(); } GUI.EndScrollView(); // reset button if (GUILayout.Button("Reset", GUILayout.Width(position.width / 5))) { layerName = "Default"; parent = null; orientToSurface = false; scaling = new Vector3(1, 1, 1); rotation = new Vector3(0, 0, 0); spaceBetween = 1; Repaint(); } // input field for setting the name of the painted prefab presetName = EditorGUILayout.TextField("Preset Name", presetName); // input field for layer name layerName = EditorGUILayout.TextField("Collision Layer", layerName); if (string.IsNullOrEmpty(layerName)) { layerName = "Default"; // change the layer name to default if user does not type in anything } //input field for setting parent of the new painted object GUILayout.BeginHorizontal(); GUILayout.Label("Hierarchy Parent"); parent = (GameObject)EditorGUILayout.ObjectField(parent, typeof(GameObject), true); GUILayout.EndHorizontal(); // check box for object orientation orientToSurface = EditorGUILayout.Toggle("Orient to Surface", orientToSurface); // slider bar to adjuste the space between objects when drag and paint GUILayout.BeginHorizontal(); GUILayout.Label("Space Between Objects"); spaceBetween = EditorGUILayout.Slider(spaceBetween, 1.0f, 100.0f); GUILayout.EndHorizontal(); // foldout field for trasnform information showWindow = EditorGUILayout.Foldout(showWindow, "Transform"); if (showWindow) { scaling = EditorGUILayout.Vector3Field("Scale", scaling); rotation = EditorGUILayout.Vector3Field("Rotation", rotation); } GUILayout.Space(5); // 'paint' and 'cancel' button GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); isPainting = GUILayout.Toggle(isPainting, "Paint", "button", GUILayout.Width(position.width / 3)); GUILayout.FlexibleSpace(); isPainting &= (!GUILayout.Button("Cancel", GUILayout.Width(position.width / 3)) && (!e.isKey || e.keyCode != KeyCode.Escape)); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.Space(30); // input area for grouping EditorGUILayout.LabelField("Grouping Presets", EditorStyles.boldLabel); GUILayout.BeginHorizontal(); groupName = EditorGUILayout.TextField("Group Name", groupName); if (string.IsNullOrEmpty(groupName)) { groupName = "New Group"; } if (GUILayout.Button("Group")) { Group(); } GUILayout.EndHorizontal(); } EditorGUILayout.EndScrollView(); }
// Check if object is an asset or a Scene object public static bool IsAsset(this object obj) { return(obj is Object && AssetDatabase.Contains((Object)obj)); }
/// <summary> /// Create the given object inside the asset cache folder path, with relative folder path. /// Depending on type, it might store in a subfolder for organizational purposes. /// </summary> /// <param name="objectToCreate">The object to create inside the asset cache</param> /// <param name="assetCacheRoot">The target path in the asset cache</param> /// <param name="relativeFolderPath">If not null or empty, the relative path to append to the assetCacheRoot. /// Otherwise uses type of asset to get subfolder name.</param> /// <param name="assetFileName">The asset's file name</param> /// <param name="type">The type of asset</param> /// <param name="bOverwriteExisting">Whether or not to overwrite if there is an existing file</param> public static void CreateObjectInAssetCacheFolder(Object objectToCreate, string assetCacheRoot, string relativeFolderPath, string assetFileName, System.Type type, bool bOverwriteExisting) { #if UNITY_EDITOR Debug.Assert(!string.IsNullOrEmpty(assetCacheRoot), "Must give valid assetCacheFolderPath to create object at"); string subFolderPath = assetCacheRoot; if (!string.IsNullOrEmpty(relativeFolderPath)) { subFolderPath = HEU_Platform.BuildPath(subFolderPath, relativeFolderPath); } else { if (type == typeof(Mesh)) { subFolderPath = AppendMeshesPathToAssetFolder(assetCacheRoot); } else if (type == typeof(Material)) { subFolderPath = AppendMaterialsPathToAssetFolder(assetCacheRoot); } else if (type == typeof(TerrainData) #if UNITY_2018_3_OR_NEWER || (type == typeof(TerrainLayer)) #else || (type == typeof(SplatPrototype)) #endif ) { subFolderPath = AppendTerrainPathToAssetFolder(assetCacheRoot); } } // Make sure subfolders exist HEU_AssetDatabase.CreatePathWithFolders(subFolderPath); // Add file name string finalAssetPath = HEU_Platform.BuildPath(subFolderPath, assetFileName); if (HEU_Platform.DoesFileExist(finalAssetPath) && !bOverwriteExisting) { finalAssetPath = AssetDatabase.GenerateUniqueAssetPath(finalAssetPath); } if (AssetDatabase.Contains(objectToCreate)) { AssetDatabase.SaveAssets(); } else { AssetDatabase.CreateAsset(objectToCreate, finalAssetPath); } // Commented out AssetDatabase.Refresh() below because its slow and seems to be unnecessary. // Leaving it commented in case need to revisit due to problems with asset creation. //RefreshAssetDatabase(); #else // TODO RUNTIME: AssetDatabase is not supported at runtime. Do we need to support this for runtime? HEU_Logger.LogWarning(HEU_Defines.HEU_USERMSG_NONEDITOR_NOT_SUPPORTED); #endif }
/// <summary> /// Shows a context menu with all game objects that owns a ParentBehaviour root. /// </summary> void ShowRootParentsSelectiontMenu() { var menu = new GenericMenu(); var objs = Resources.FindObjectsOfTypeAll(typeof(ParentBehaviour)); // get parents var gameObjectsInMenu = new List <GameObject>(); // Game objects already added to the menu var uniqueNames = new List <string>(); // Game objects names in the menu var activeGameObject = activeParent != null ? activeParent.gameObject : null; int i = 0; foreach (ParentBehaviour parent in objs) { // Is a root parent? if (parent.isRoot) { var gameObject = parent.gameObject; // The game object is not null and it is not yet in the menu? if (gameObject != null && !gameObjectsInMenu.Contains(gameObject)) { gameObjectsInMenu.Add(gameObject); uniqueNames.Add(StringHelper.GetUniqueNameInList(uniqueNames, gameObject.name + (AssetDatabase.Contains(gameObject) ? " (Prefab)" : string.Empty))); menu.AddItem(new GUIContent(uniqueNames[i]), activeGameObject == gameObject, delegate() { Selection.activeObject = gameObject; }); ++i; } } } menu.ShowAsContext(); }
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(); }
static internal void BuildMenu(GenericMenu menu, PEPrefabScript prefabInstance, bool rootPrefab, string path = "", bool showParent = true, bool showInstances = true) { prefabInstance.CheckPrefab(); if (buildMenuRecursionList.Contains(prefabInstance.Prefab)) { buildMenuRecursionList.AddLast(prefabInstance.Prefab); var prefabsArray = buildMenuRecursionList.Select(p => AssetDatabase.GetAssetPath(p)).ToArray(); buildMenuRecursionList.Clear(); throw new System.Exception("Prefab recursion detected:\n" + string.Join("\n", prefabsArray)); } buildMenuRecursionList.AddLast(prefabInstance.Prefab); if (prefabInstance.ParentPrefab == null || !showParent) { menu.AddItem(new GUIContent(path + prefabInstance.Prefab.name), false, () => { }); } else { BuildMenu(menu, prefabInstance.ParentPrefab.GetComponent <PEPrefabScript>(), false, path + prefabInstance.Prefab.name + "/", true, false); menu.AddItem(new GUIContent(path + prefabInstance.Prefab.name), false, () => { }); } menu.AddSeparator(path + ""); var isPrefab = prefabInstance.gameObject == prefabInstance.Prefab.gameObject; menu.AddItem(new GUIContent(path + "Select"), false, SelectPrefab, prefabInstance); var prefabType = PrefabUtility.GetPrefabType(prefabInstance.gameObject); var canApply = rootPrefab && prefabType != PrefabType.ModelPrefab && prefabType != PrefabType.ModelPrefabInstance && prefabType != PrefabType.DisconnectedModelPrefabInstance; if (canApply) { menu.AddItem(new GUIContent(path + "Apply"), false, Apply, prefabInstance); } if (!AssetDatabase.Contains(prefabInstance) || !isPrefab) { menu.AddItem(new GUIContent(path + "Revert"), false, Revert, prefabInstance); if (prefabInstance.ParentPrefab != null) { menu.AddItem(new GUIContent(path + "Revert To Parent"), false, RevertToParent, prefabInstance); } } menu.AddSeparator(path + ""); menu.AddItem(new GUIContent(path + "Create Child"), false, CreateChild, prefabInstance); #if INJECTION if (prefabInstance.ParentPrefab != null) { menu.AddItem(new GUIContent(path + "Insert Parent"), false, InjectParent, prefabInstance); } #endif if (!rootPrefab && !AssetDatabase.Contains(prefabInstance)) { menu.AddSeparator(path); if (prefabInstance.enabled) { menu.AddItem(new GUIContent(path + "Disable"), false, obj => (obj as PEPrefabScript).enabled = false, prefabInstance); } else { menu.AddItem(new GUIContent(path + "Enable"), false, obj => (obj as PEPrefabScript).enabled = true, prefabInstance); } } menu.AddSeparator(path); if (prefabInstance.GetPrefabsWithInstances().Any()) { menu.AddItem(new GUIContent(path + "Instances/Select All Instances"), false, SelectInstances, prefabInstance); } if (showInstances) { foreach (var prefab in prefabInstance.GetPrefabsWithInstances()) { if (prefab == null) { continue; } var pi = prefab.GetComponent <PEPrefabScript>(); var name = prefab.name; name = (pi != null && pi.ParentPrefab == prefabInstance.Prefab) ? "Child: " + name : "Contains in: " + name; if (pi != null) { BuildMenu(menu, prefab.GetComponent <PEPrefabScript>(), false, path + "Instances/" + name + "/", false); } var current = prefab; menu.AddItem(new GUIContent(path + "Instances/" + name), false, () => { Selection.activeObject = current; }); } } menu.AddItem(new GUIContent(path + "Instantiate"), false, pi => Selection.activeObject = PrefabUtility.InstantiatePrefab(((PEPrefabScript)pi).Prefab), prefabInstance); if (!AssetDatabase.Contains(prefabInstance)) { menu.AddItem(new GUIContent(path + "Replace"), false, Replace, prefabInstance); } buildMenuRecursionList.Remove(prefabInstance.Prefab); }
public static void AddMaterials(MeshRenderer[] renderers, SkinnedMeshRenderer[] skinnedRenderers, AssetImportContext ctx) { HashSet <Material> visitedMaterials = new HashSet <Material>(); HashSet <Texture2D> visitedTextures = new HashSet <Texture2D>(); for (int i = 0; i < renderers.Length; i++) { foreach (Material mat in renderers[i].sharedMaterials) { if (mat == GLTFMaterial.defaultMaterial) { continue; } if (visitedMaterials.Contains(mat)) { continue; } if (string.IsNullOrEmpty(mat.name)) { mat.name = "material" + visitedMaterials.Count; } ctx.AddAsset(mat.name, mat); visitedMaterials.Add(mat); // Add textures foreach (Texture2D tex in mat.AllTextures()) { // Dont add asset textures //if (images[i].isAsset) continue; if (visitedTextures.Contains(tex)) { continue; } if (AssetDatabase.Contains(tex)) { continue; } if (string.IsNullOrEmpty(tex.name)) { tex.name = "texture" + visitedTextures.Count; } ctx.AddAsset(tex.name, tex); visitedTextures.Add(tex); } } } for (int i = 0; i < skinnedRenderers.Length; i++) { foreach (Material mat in skinnedRenderers[i].sharedMaterials) { if (visitedMaterials.Contains(mat)) { continue; } if (string.IsNullOrEmpty(mat.name)) { mat.name = "material" + visitedMaterials.Count; } ctx.AddAsset(mat.name, mat); visitedMaterials.Add(mat); // Add textures foreach (Texture2D tex in mat.AllTextures()) { // Dont add asset textures //if (images[i].isAsset) continue; if (visitedTextures.Contains(tex)) { continue; } if (AssetDatabase.Contains(tex)) { continue; } if (string.IsNullOrEmpty(tex.name)) { tex.name = "texture" + visitedTextures.Count; } ctx.AddAsset(tex.name, tex); visitedTextures.Add(tex); } } } }
public static void CreateVisual() { if (Selection.activeGameObject == null) { Debug.Log("Unable to create visual: No game object selected in scene."); return; } if (AssetDatabase.Contains(Selection.activeGameObject)) { Debug.Log("Unable to create visual: Selected game object is not an instance in a scene.", Selection.activeGameObject); return; } var shapes = Selection.activeGameObject.GetComponentsInChildren <Shape>(); if (shapes.Length == 0) { Debug.Log("Unable to create visual: Selected game object doesn't have any shapes.", Selection.activeGameObject); return; } int numValidCreateVisual = 0; int numSensors = 0; foreach (var shape in shapes) { var validForVisual = !ShapeVisual.HasShapeVisual(shape) && ShapeVisual.SupportsShapeVisual(shape); numValidCreateVisual += Convert.ToInt32(validForVisual); numSensors += Convert.ToInt32(validForVisual && shape.IsSensor); } var createVisualForSensors = false; if (numSensors > 0) { createVisualForSensors = EditorUtility.DisplayDialog("Sensors", "There are " + numSensors + " sensors in this object. Would you like to create visuals for sensors as well?", "Yes", "No"); } if (numValidCreateVisual == 0 || numSensors >= numValidCreateVisual) { Debug.Log("Create visual ignored: All shapes already have visual data or doesn't support to be visualized.", Selection.activeGameObject); return; } Undo.SetCurrentGroupName("Create GameObject shape visual."); var grouId = Undo.GetCurrentGroup(); foreach (var shape in shapes) { var createVisual = !ShapeVisual.HasShapeVisual(shape) && (createVisualForSensors || !shape.IsSensor); if (createVisual) { var go = ShapeVisual.Create(shape); if (go != null) { Undo.RegisterCreatedObjectUndo(go, "Shape visual"); } } } Undo.CollapseUndoOperations(grouId); }
public static bool IsSubAsset(UnityEngine.Object obj) { return(obj != null && AssetDatabase.Contains(obj) && AssetDatabase.IsSubAsset(obj)); }
static void CreatePrefab() { if (Selection.activeGameObject != null) { if (!Directory.Exists("Assets/MegaPrefabs")) { AssetDatabase.CreateFolder("Assets", "MegaPrefabs"); } GameObject obj = Selection.activeGameObject; // Make a copy? GameObject newobj = MegaCopyObject.DuplicateObjectForPrefab(obj); newobj.name = obj.name; // Get all modifyObjects in children MegaModifyObject[] mods = newobj.GetComponentsInChildren <MegaModifyObject>(); int id = 0; for (int i = 0; i < mods.Length; i++) { // Need method to get the base mesh GameObject pobj = mods[i].gameObject; // Get the mesh and make an asset for it //Mesh mesh = MegaUtils.GetSharedMesh(pobj); GameObject inobj = null; Mesh mesh = MegaModifyObject.FindMesh(pobj, out inobj); if (mesh) { if (!AssetDatabase.Contains(mesh)) { string mname = mesh.name; int ix = mname.IndexOf("Instance"); if (ix != -1) { mname = mname.Remove(ix); } string meshpath = "Assets/MegaPrefabs/" + mname + ".prefab"; id++; AssetDatabase.CreateAsset(mesh, meshpath); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } } } MegaWrap[] wraps = newobj.GetComponentsInChildren <MegaWrap>(); for (int i = 0; i < wraps.Length; i++) { // Need method to get the base mesh GameObject pobj = wraps[i].gameObject; // Get the mesh and make an asset for it //Mesh mesh = MegaUtils.GetSharedMesh(pobj); GameObject inobj = null; Mesh mesh = MegaModifyObject.FindMesh(pobj, out inobj); if (mesh) { if (!AssetDatabase.Contains(mesh)) { string mname = mesh.name; int ix = mname.IndexOf("Instance"); if (ix != -1) { mname = mname.Remove(ix); } string meshpath = "Assets/MegaPrefabs/" + mname + ".prefab"; id++; AssetDatabase.CreateAsset(mesh, meshpath); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } } } Object prefab = PrefabUtility.CreateEmptyPrefab("Assets/MegaPrefabs/" + newobj.name + "_Prefab.prefab"); //EditorUtility.ReplacePrefab(newobj, prefab, ReplacePrefabOptions.ConnectToPrefab); PrefabUtility.ReplacePrefab(newobj, prefab, ReplacePrefabOptions.ConnectToPrefab); DestroyImmediate(newobj, 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); } }
private void ColorRamp(string inspector, string keyword) { bool toggle = oldKeyWords.Contains(keyword); bool ini = toggle; GUIContent effectNameLabel = new GUIContent(); effectNameLabel.tooltip = keyword + " (C#)"; effectNameLabel.text = effectCount + "." + inspector; toggle = EditorGUILayout.BeginToggleGroup(effectNameLabel, toggle); effectCount++; if (ini != toggle) { Save(); } if (toggle) { targetMat.EnableKeyword("COLORRAMP_ON"); EditorGUILayout.BeginVertical(propertiesStyle); { bool useEditableGradient = false; if (AssetDatabase.Contains(targetMat)) { useEditableGradient = oldKeyWords.Contains("GRADIENTCOLORRAMP_ON"); bool gradientTex = useEditableGradient; gradientTex = GUILayout.Toggle(gradientTex, new GUIContent("Use Editable Gradient?")); if (useEditableGradient != gradientTex) { Save(); if (gradientTex) { useEditableGradient = true; targetMat.EnableKeyword("GRADIENTCOLORRAMP_ON"); } else { targetMat.DisableKeyword("GRADIENTCOLORRAMP_ON"); } } if (useEditableGradient) { matEditor.ShaderProperty(matProperties[159], matProperties[159].displayName); } } else { GUILayout.Label("*Save to folder to allow for dynamic Gradient property", smallLabelStyle); } if (!useEditableGradient) { DrawProperty(51); } DrawProperty(52); DrawProperty(53, true); MaterialProperty colorRampOut = matProperties[53]; if (colorRampOut.floatValue == 1) { targetMat.EnableKeyword("COLORRAMPOUTLINE_ON"); } else { targetMat.DisableKeyword("COLORRAMPOUTLINE_ON"); } DrawProperty(155); } EditorGUILayout.EndVertical(); } else { targetMat.DisableKeyword("COLORRAMP_ON"); } EditorGUILayout.EndToggleGroup(); }
internal virtual bool SaveToAssetDatabase(Object parentAsset, bool saveAssetDatabase) { if (s_Debug) { Debug.Log("SaveToAssetDatabase: " + this.name + (parentAsset == null ? "" : " to: " + parentAsset.name)); } if (!Application.isPlaying && !AssetDatabase.Contains(this)) { if (parentAsset == null) { if (s_Debug) { Debug.Log("No parentAsset is provided. Creating a new main asset."); } string filePath = AssetDatabase.GetAssetPath(Selection.activeObject); string fileName = "/" + name + ".asset"; if (string.IsNullOrEmpty(filePath)) { filePath = "Assets"; } else if (System.IO.Path.GetExtension(filePath) != "") { filePath = filePath.Replace(System.IO.Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), ""); } string assetPath = AssetDatabase.GenerateUniqueAssetPath(filePath + fileName); this.hideFlags = HideFlags.None; AssetDatabase.CreateAsset(this, assetPath); } else if (!AssetDatabase.Contains(parentAsset)) { if (s_Debug) { Debug.Log("A parentAsset is provided but didn't save the parent first. This condition should not occur."); } string filePath = AssetDatabase.GetAssetPath(Selection.activeObject); string fileName = "/" + parentAsset.name + ".asset"; if (string.IsNullOrEmpty(filePath)) { filePath = "Assets"; } else if (System.IO.Path.GetExtension(filePath) != "") { filePath = filePath.Replace(System.IO.Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), ""); } string assetPath = AssetDatabase.GenerateUniqueAssetPath(filePath + fileName); parentAsset.hideFlags = HideFlags.None; AssetDatabase.CreateAsset(parentAsset, assetPath); this.hideFlags = s_Debug || parentAsset is GameObject ? HideFlags.None : HideFlags.HideInHierarchy; AssetDatabase.AddObjectToAsset(this, parentAsset); } else { if (s_Debug) { Debug.Log("A parentAsset is provided and it's already in the AssetDatabase, then we add this as a subAsset of the parent."); } this.hideFlags = s_Debug || parentAsset is GameObject ? HideFlags.None : HideFlags.HideInHierarchy; AssetDatabase.AddObjectToAsset(this, parentAsset); } if (saveAssetDatabase) { AssetDatabase.SaveAssets(); } return(true); } else { Debug.Log("Cannot save asset. " + this.name + " is already saved to the AssetDatabase."); return(false); } }
public static void ApplyDefaultTextureSettings() { if (Prefs == null) { LoadPrefs(); } foreach (var obj in Selection.objects) { if (!AssetDatabase.Contains(obj)) { continue; } string path = AssetDatabase.GetAssetPath(obj); var importer = AssetImporter.GetAtPath(path) as TextureImporter; if (importer == null) { continue; } TextureImporterSettings settings = new TextureImporterSettings(); // Try to slice it first var fileName = Path.GetFileNameWithoutExtension(path); var size = GetSize(path, Prefs.SizeDetectionRegex); if (size != Vector2.zero) { importer.spriteImportMode = SpriteImportMode.Multiple; var gridRects = InternalSpriteUtility.GenerateGridSpriteRectangles( AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D, Vector2.zero, size, Vector2.zero); importer.spritesheet = gridRects .Select(x => new SpriteMetaData { alignment = (int)Prefs.SpriteAlignment, name = fileName + "_" + Array.IndexOf(gridRects, x), rect = x }).ToArray(); } else { importer.spriteImportMode = SpriteImportMode.Single; } importer.ReadTextureSettings(settings); settings.filterMode = Prefs.FilterMode; settings.wrapMode = Prefs.WrapMode; settings.mipmapEnabled = Prefs.EnableMipMaps; settings.textureFormat = Prefs.TextureFormat; settings.spritePixelsPerUnit = Prefs.PixelsPerUnit; settings.spriteAlignment = (int)Prefs.SpriteAlignment; settings.spriteExtrude = Prefs.SpriteExtrude; settings.spriteMeshType = Prefs.SpriteMeshType; importer.SetTextureSettings(settings); AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate); EditorUtility.SetDirty(obj); } }
public void DropAreaGUI() { Event evt = Event.current; Rect drop_area = new Rect(0, 0, EditorGUIUtility.currentViewWidth, position.height); switch (evt.type) { case EventType.DragUpdated: case EventType.DragPerform: if (!drop_area.Contains(evt.mousePosition)) { return; } DragAndDrop.visualMode = DragAndDropVisualMode.Generic; if (evt.type == EventType.DragPerform) { DragAndDrop.AcceptDrag(); List <EntryData> duplicateList = new List <EntryData>(); List <EntryData> allowedList = new List <EntryData>(); foreach (UnityEngine.Object draggedObject in DragAndDrop.objectReferences) { if (!AssetDatabase.Contains(draggedObject)) { EditorUtility.DisplayDialog("Bookmark Everything", "Objects from hierarchy is not supported for now. Would you like me to add that? Please e-mail me at [email protected].", "Okay"); return; } EntryData entryData = new EntryData(draggedObject); if (_tempLocations.Contains(entryData, new EntryDataGUIDComparer())) { duplicateList.Add(_tempLocations.Find((entry) => entry.GUID == entryData.GUID)); } else { allowedList.Add(entryData); } } if (duplicateList.Count > 0) { StringBuilder sb = new StringBuilder(); sb.Append("\n\n"); for (int i = 0; i < duplicateList.Count; i++) { sb.Append(string.Format("{0} in {1} Category\n\n", GetNameForFile(AssetDatabase.GUIDToAssetPath(duplicateList[i].GUID)), duplicateList[i].Category)); } if (EditorUtility.DisplayDialog("Bookmark Everything", string.Format("Duplicate Entries Found: {0} Would you still like to add them ?(Non-duplicates will be added anyway)", sb.ToString()), "Yes", "No")) { duplicateList.AddRange(allowedList); for (int i = 0; i < duplicateList.Count; i++) { if (_tabIndex == 0) { duplicateList[i].Category = GetNameOfCategory(_projectFinderTabIndex); duplicateList[i].Index = _projectFinderTabIndex; } else if (_tabIndex == 1) { duplicateList[i].Category = GetNameOfCategory(0); duplicateList[i].Index = 0; _lastlyAddedCount++; } } _tempLocations.AddRange(duplicateList); if (_tabIndex == 0) { SaveChanges(); } // else if (_tabIndex == 1) // { // _changesMade = true; // } } else { for (int i = 0; i < allowedList.Count; i++) { if (_tabIndex == 0) { allowedList[i].Category = GetNameOfCategory(_projectFinderTabIndex); allowedList[i].Index = _projectFinderTabIndex; } else if (_tabIndex == 1) { allowedList[i].Category = GetNameOfCategory(0); allowedList[i].Index = 0; _lastlyAddedCount++; } } _tempLocations.AddRange(allowedList); if (_tabIndex == 0) { SaveChanges(); } // else if (_tabIndex == 1) // { // _changesMade = true; // } } } else if (allowedList.Count > 0) { for (int i = 0; i < allowedList.Count; i++) { if (_tabIndex == 0) { allowedList[i].Category = GetNameOfCategory(_projectFinderTabIndex); allowedList[i].Index = _projectFinderTabIndex; } else if (_tabIndex == 1) { allowedList[i].Category = GetNameOfCategory(0); allowedList[i].Index = 0; _lastlyAddedCount++; } } _tempLocations.AddRange(allowedList); if (_tabIndex == 0) { SaveChanges(); } // else if (_tabIndex == 1) // { // _changesMade = true; // } } } break; } }
public override void GenerateOnly() { if (voxelObject == null || voxelObjectCore.voxelData == null) { return; } var voxelData = voxelObjectCore.voxelData; //BasicCube Vector3 cubeCenter; List <Vector3> cubeVertices; List <Vector3> cubeNormals; List <int> cubeTriangles; CreateBasicCube(out cubeCenter, out cubeVertices, out cubeNormals, out cubeTriangles); #region Voxels List <Vector3> vertices = new List <Vector3>(); List <Vector3> normals = new List <Vector3>(); List <Color> colors = new List <Color>(); List <Vector4> tangents = new List <Vector4>(); List <int>[] triangles = new List <int> [voxelBase.materialData.Count]; for (int i = 0; i < triangles.Length; i++) { triangles[i] = new List <int>(); } #region Mesh Func <VoxelObjectExplosion.MeshData, VoxelObjectExplosion.MeshData> CreateMesh = (data) => { if (data == null) { data = new VoxelObjectExplosion.MeshData(); } if (data.mesh == null) { data.mesh = new Mesh(); } else { data.mesh.Clear(false); data.mesh.ClearBlendShapes(); } data.materialIndexes.Clear(); #if UNITY_2017_3_OR_NEWER data.mesh.indexFormat = vertices.Count > 65000 ? UnityEngine.Rendering.IndexFormat.UInt32 : UnityEngine.Rendering.IndexFormat.UInt16; #endif data.mesh.vertices = vertices.ToArray(); data.mesh.normals = normals.ToArray(); data.mesh.colors = colors.ToArray(); data.mesh.tangents = tangents.ToArray(); { int materialCount = 0; for (int i = 0; i < triangles.Length; i++) { if (triangles[i].Count > 0) { materialCount++; } } data.mesh.subMeshCount = materialCount; int submesh = 0; for (int i = 0; i < triangles.Length; i++) { if (triangles[i].Count > 0) { data.materialIndexes.Add(i); data.mesh.SetTriangles(triangles[i].ToArray(), submesh++); } } } data.mesh.RecalculateBounds(); { var bounds = data.mesh.bounds; bounds.min -= Vector3.one * explosionBase.edit_velocityMax; bounds.max += Vector3.one * explosionBase.edit_velocityMax; data.mesh.bounds = bounds; } vertices.Clear(); normals.Clear(); colors.Clear(); tangents.Clear(); for (int i = 0; i < voxelBase.materialData.Count; i++) { triangles[i].Clear(); } return(data); }; #endregion { int meshIndex = 0; Action <int, int> AddVertex = (mat, index) => { if (explosionBase.edit_birthRate < 1f) { if (UnityEngine.Random.value >= explosionBase.edit_birthRate) { return; } } if (explosionBase.edit_visibleOnly) { if (!voxelObjectCore.IsVoxelVisible(voxelData.voxels[index].position)) { return; } } #if !UNITY_2017_3_OR_NEWER if (vertices.Count + cubeVertices.Count >= 65000) { for (int i = explosionObject.meshes.Count; i <= meshIndex; i++) { explosionObject.meshes.Add(null); } explosionObject.meshes[meshIndex] = CreateMesh(explosionObject.meshes[meshIndex]); if (!AssetDatabase.Contains(explosionObject.meshes[meshIndex].mesh)) { voxelBaseCore.AddObjectToPrefabAsset(explosionObject.meshes[meshIndex].mesh, "explosion_mesh", meshIndex); } meshIndex++; } #endif var color = voxelData.palettes[voxelData.voxels[index].palette]; var vOffset = vertices.Count; for (int i = 0; i < cubeVertices.Count; i++) { var pos = cubeVertices[i]; pos.x += voxelData.voxels[index].position.x * voxelBase.importScale.x; pos.y += voxelData.voxels[index].position.y * voxelBase.importScale.y; pos.z += voxelData.voxels[index].position.z * voxelBase.importScale.z; vertices.Add(pos); } normals.AddRange(cubeNormals); for (int j = 0; j < cubeTriangles.Count; j++) { triangles[mat].Add(vOffset + cubeTriangles[j]); } for (int j = 0; j < cubeVertices.Count; j++) { colors.Add(color); } { Vector3 center = new Vector3 ( center.x = cubeCenter.x + voxelData.voxels[index].position.x * voxelBase.importScale.x, center.y = cubeCenter.y + voxelData.voxels[index].position.y * voxelBase.importScale.y, center.z = cubeCenter.z + voxelData.voxels[index].position.z * voxelBase.importScale.z ); var velocity = UnityEngine.Random.Range(explosionBase.edit_velocityMin, explosionBase.edit_velocityMax); for (int j = 0; j < cubeVertices.Count; j++) { tangents.Add(new Vector4(center.x - vertices[vOffset + j].x, center.y - vertices[vOffset + j].y, center.z - vertices[vOffset + j].z, velocity)); } } }; if (explosionObject.meshes == null) { explosionObject.meshes = new List <VoxelObjectExplosion.MeshData>(); } FlagTable3 doneTable = new FlagTable3(voxelData.voxelSize.x, voxelData.voxelSize.y, voxelData.voxelSize.z); for (int i = 1; i < voxelBase.materialData.Count; i++) { voxelBase.materialData[i].AllAction((pos) => { doneTable.Set(pos, true); var index = voxelData.VoxelTableContains(pos); if (index < 0) { return; } AddVertex(i, index); }); } for (int index = 0; index < voxelData.voxels.Length; index++) { if (doneTable.Get(voxelData.voxels[index].position)) { continue; } AddVertex(0, index); } if (vertices.Count > 0) { for (int i = explosionObject.meshes.Count; i <= meshIndex; i++) { explosionObject.meshes.Add(null); } explosionObject.meshes[meshIndex] = CreateMesh(explosionObject.meshes[meshIndex]); if (!AssetDatabase.Contains(explosionObject.meshes[meshIndex].mesh)) { voxelBaseCore.AddObjectToPrefabAsset(explosionObject.meshes[meshIndex].mesh, "explosion_mesh", meshIndex); } meshIndex++; } explosionObject.meshes.RemoveRange(meshIndex, explosionObject.meshes.Count - meshIndex); } #endregion #region Material if (explosionObject.materials == null) { explosionObject.materials = new List <Material>(); } if (explosionObject.materials.Count < voxelBase.materialData.Count) { for (int i = explosionObject.materials.Count; i < voxelBase.materialData.Count; i++) { explosionObject.materials.Add(null); } } else if (explosionObject.materials.Count > voxelBase.materialData.Count) { explosionObject.materials.RemoveRange(voxelBase.materialData.Count, explosionObject.materials.Count - voxelBase.materialData.Count); } for (int i = 0; i < voxelBase.materialData.Count; i++) { if (explosionObject.materials[i] == null) { if (!voxelBase.materialData[i].transparent) { explosionObject.materials[i] = new Material(Shader.Find("Voxel Importer/Explosion/VoxelExplosion-Opaque")); } else { explosionObject.materials[i] = new Material(Shader.Find("Voxel Importer/Explosion/VoxelExplosion-Transparent")); } } else { if (!voxelBase.materialData[i].transparent) { explosionObject.materials[i].shader = Shader.Find("Voxel Importer/Explosion/VoxelExplosion-Opaque"); if (!AssetDatabase.Contains(explosionObject.materials[i])) { explosionObject.materials[i].name = "Voxel Importer/Explosion/VoxelExplosion-Opaque"; } } else { explosionObject.materials[i].shader = Shader.Find("Voxel Importer/Explosion/VoxelExplosion-Transparent"); if (!AssetDatabase.Contains(explosionObject.materials[i])) { explosionObject.materials[i].name = "Voxel Importer/Explosion/VoxelExplosion-Transparent"; } } } if (!AssetDatabase.Contains(explosionObject.materials[i])) { voxelBaseCore.AddObjectToPrefabAsset(explosionObject.materials[i], "explosion_mat", i); } } #endregion }
public static bool IsInPrefabAsset(this Component component) { return(AssetDatabase.Contains(component.transform.root.gameObject)); }