/// <summary> // This makes it easy to create, name and place unique new ScriptableObject asset files. /// </summary> public static void CreateAsset <T> () where T : ScriptableObject { T asset = ScriptableObject.CreateInstance <T> (); string path = AssetDatabase.GetAssetPath(Selection.activeObject); if (path == "") { path = "Assets"; } else if (Path.GetExtension(path) != "") { path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), ""); } string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath(path + "/New " + typeof(T).ToString() + ".asset"); AssetDatabase.CreateAsset(asset, assetPathAndName); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); EditorUtility.FocusProjectWindow(); Selection.activeObject = asset; }
static void CreateAtlas() { GiraffeSpriteAnimation font = ScriptableObject.CreateInstance <GiraffeSpriteAnimation>(); string path = AssetDatabase.GetAssetPath(Selection.activeObject); if (path == "") { path = "Assets"; } else if (Path.GetExtension(path) != "") { path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), ""); } string fontPath = AssetDatabase.GenerateUniqueAssetPath(path + "/New Giraffe Spite Animation.asset"); AssetDatabase.CreateAsset(font, fontPath); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); EditorUtility.FocusProjectWindow(); Selection.activeObject = font; }
public override void Action(int instanceId, string pathName, string resourceFile) { UnityEngine.Object obj = EditorUtility.InstanceIDToObject(instanceId); AssetDatabase.CreateAsset(obj, AssetDatabase.GenerateUniqueAssetPath(pathName)); AmplifyShaderEditorWindow.LoadShaderFunctionToASE((AmplifyShaderFunction)obj, false); }
public GameObject MakeFromVerts(bool ReverseNormals, Vector3[] vertsToCopy, List <int> pathSplitIds, GameObject FFDGameObject) { bool overwrite = false; MeshedSprite = new GameObject(); Undo.RegisterCreatedObjectUndo(MeshedSprite, "Created Mesh"); mf = MeshedSprite.AddComponent <MeshFilter>(); mr = MeshedSprite.AddComponent <MeshRenderer>(); mesh = new Mesh(); if (AssetDatabase.LoadAssetAtPath(Puppet2D_Editor._puppet2DPath + "/Models/" + FFDGameObject.transform.name + "_MESH.asset", typeof(Mesh))) { if (EditorUtility.DisplayDialog("Overwrite Asset?", "Do you want to overwrite the current Mesh & Material?", "Yes, Overwrite", "No, Create New Mesh & Material")) { //mf.mesh = AssetDatabase.LoadAssetAtPath(Puppet2D_Editor._puppet2DPath+"/Models/"+transform.name+"_MESH.asset",typeof(Mesh))as Mesh; string meshPath = (Puppet2D_Editor._puppet2DPath + "/Models/" + FFDGameObject.transform.name + "_MESH.asset"); AssetDatabase.CreateAsset(mesh, meshPath); overwrite = true; } else { string meshPath = AssetDatabase.GenerateUniqueAssetPath(Puppet2D_Editor._puppet2DPath + "/Models/" + FFDGameObject.transform.name + "_MESH.asset"); AssetDatabase.CreateAsset(mesh, meshPath); } } else { string meshPath = AssetDatabase.GenerateUniqueAssetPath(Puppet2D_Editor._puppet2DPath + "/Models/" + FFDGameObject.transform.name + "_MESH.asset"); AssetDatabase.CreateAsset(mesh, meshPath); } mesh = CreateMeshFromVerts(vertsToCopy, mesh, pathSplitIds, FFDGameObject.transform); mf.mesh = mesh; results.Clear(); resultsTriIndexes.Clear(); resultsTriIndexesReversed.Clear(); uvs.Clear(); normals.Clear(); if (overwrite) { mr.material = AssetDatabase.LoadAssetAtPath(Puppet2D_Editor._puppet2DPath + "/Models/Materials/" + FFDGameObject.transform.name + "_MAT.mat", typeof(Material)) as Material; } else { Material newMat = new Material(Shader.Find("Unlit/Transparent")); string materialPath = AssetDatabase.GenerateUniqueAssetPath(Puppet2D_Editor._puppet2DPath + "/Models/Materials/" + FFDGameObject.transform.name + "_MAT.mat"); AssetDatabase.CreateAsset(newMat, materialPath); mr.material = newMat; } return(MeshedSprite); }
public static void ReadMesh(string path, string filename, string texturepath) { if (File.Exists(path + "/" + filename)) { const Assimp.PostProcessSteps flags = ( // Assimp.PostProcessSteps.MakeLeftHanded | Assimp.PostProcessSteps.OptimizeMeshes | Assimp.PostProcessSteps.OptimizeGraph | Assimp.PostProcessSteps.RemoveRedundantMaterials | Assimp.PostProcessSteps.SortByPrimitiveType | Assimp.PostProcessSteps.SplitLargeMeshes | Assimp.PostProcessSteps.Triangulate | Assimp.PostProcessSteps.CalculateTangentSpace | Assimp.PostProcessSteps.GenerateUVCoords | Assimp.PostProcessSteps.GenerateSmoothNormals | Assimp.PostProcessSteps.RemoveComponent | Assimp.PostProcessSteps.JoinIdenticalVertices ); var config = Assimp.aiCreatePropertyStore(); Assimp.aiSetImportPropertyFloat(config, Assimp.AI_CONFIG_PP_CT_MAX_SMOOTHING_ANGLE, 60.0f); // IntPtr scene = Assimp.aiImportFile(path + "/" + filename, (uint)flags); var scene = Assimp.aiImportFileWithProperties(path + "/" + filename, (uint)flags, config); Assimp.aiReleasePropertyStore(config); if (scene == null) { Debug.LogWarning("failed to read file: " + path + "/" + filename); return; } else { var nm = Path.GetFileNameWithoutExtension(filename); var importingAssetsDir = "Assets/Prefabs/" + nm + "/"; if (_SaveAssets) { if (!Directory.Exists(importingAssetsDir)) { Directory.CreateDirectory(importingAssetsDir); } AssetDatabase.Refresh(); } var objectRoot = new GameObject(nm); var meshContainer = new GameObject(nm + "_Mesh"); meshContainer.transform.parent = objectRoot.transform; var materials = new List <Material>(); var meshList = new List <AssimpMesh>(); for (var i = 0; i < Assimp.aiScene_GetNumMaterials(scene); i++) { var matName = Assimp.aiMaterial_GetName(scene, i); matName = nm + "_mat" + i; // string fname = Path.GetFileNameWithoutExtension(Assimp.aiMaterial_GetTexture(scene, i, (int)Assimp.TextureType.Diffuse)); var file_name = Path.GetFileName(Assimp.aiMaterial_GetTexture(scene, i, (int)Assimp.TextureType.Diffuse)); Debug.Log("texture " + file_name + "Material :" + matName); var ambient = Assimp.aiMaterial_GetAmbient(scene, i); var diffuse = Assimp.aiMaterial_GetDiffuse(scene, i); var specular = Assimp.aiMaterial_GetSpecular(scene, i); var emissive = Assimp.aiMaterial_GetEmissive(scene, i); var mat = new Material(Shader.Find("Diffuse")) { name = matName }; var textureName = path + "/" + file_name; var tex = Utils.LoadTex(textureName); //Texture2D tex = Resources.Load(texturename) as Texture2D; //Texture2D tex = (Texture2D)AssetDatabase.LoadAssetAtPath(texturename, typeof(Texture2D)); if (tex != null) { Debug.Log("LOAD (" + textureName + ") texture"); mat.SetTexture("_MainTex", tex); } else { Debug.LogError("Fail LOAD (" + textureName + ") error"); } if (_SaveAssets) { var materialAssetPath = AssetDatabase.GenerateUniqueAssetPath(importingAssetsDir + mat.name + ".asset"); AssetDatabase.CreateAsset(mat, materialAssetPath); } materials.Add(mat); } AssetDatabase.Refresh(); if (Assimp.aiScene_HasMeshes(scene)) { for (var i = 0; i < Assimp.aiScene_GetNumMeshes(scene); i++) { var name = "Mesh_"; name += i.ToString(); var hasNormals = Assimp.aiMesh_HasNormals(scene, i); var hasTexCoord = Assimp.aiMesh_HasTextureCoords(scene, i, 0); var hasFaces = Assimp.aiMesh_HasFaces(scene, i); var mesh = new AssimpMesh(meshContainer, objectRoot, name); mesh.SetMaterial(materials[Assimp.aiMesh_GetMaterialIndex(scene, i)]); meshList.Add(mesh); for (var v = 0; v < Assimp.aiMesh_GetNumVertices(scene, i); v++) { var vertex = Assimp.aiMesh_Vertex(scene, i, v); var n = Assimp.aiMesh_Normal(scene, i, v); var x = Assimp.aiMesh_TextureCoordX(scene, i, v, 0); var y = Assimp.aiMesh_TextureCoordY(scene, i, v, 0); var binormalf = Assimp.aiMesh_Bitangent(scene, i, v); var tangentf = Assimp.aiMesh_Tangent(scene, i, v); var outputTangent = new Vector4(tangentf.x, tangentf.y, tangentf.z, 0.0F); var dp = Vector3.Dot(Vector3.Cross(n, tangentf), binormalf); if (dp > 0.0F) { outputTangent.w = 1.0F; } else { outputTangent.w = -1.0F; } mesh.AddVertex(vertex, n, new Vector2(x, y), outputTangent); //mesh.addVertex(vertex, new Vector3(1 * -n.x, n.y, n.z), new Vector2(x, y), outputTangent); } for (var f = 0; f < Assimp.aiMesh_GetNumFaces(scene, i); f++) { var a = Assimp.aiMesh_Indice(scene, i, f, 0); var b = Assimp.aiMesh_Indice(scene, i, f, 1); var c = Assimp.aiMesh_Indice(scene, i, f, 2); mesh.AddFace(a, b, c); } //********** mesh.Build(); if (_SaveAssets) { var meshAssetPath = AssetDatabase.GenerateUniqueAssetPath(importingAssetsDir + mesh._Name + ".asset"); AssetDatabase.CreateAsset(mesh._Geometry, meshAssetPath); } mesh.Dispose(); } } if (_SaveAssets) { var prefabPath = AssetDatabase.GenerateUniqueAssetPath(importingAssetsDir + filename + ".prefab"); var prefab = PrefabUtility.CreateEmptyPrefab(prefabPath); PrefabUtility.ReplacePrefab(objectRoot, prefab, ReplacePrefabOptions.ConnectToPrefab); AssetDatabase.Refresh(); } meshList.Clear(); } Assimp.aiReleaseImport(scene); Debug.LogWarning(path + "/" + filename + " Imported ;) "); } }
void TryGUI() { SpriteSheet newSheet = (SpriteSheet)EditorGUILayout.ObjectField("Sheet", this.editedSheet, typeof(SpriteSheet), false); if (this.editedSheet != newSheet || this.isReloaded) { this.isReloaded = false; this.editedSheet = newSheet; if (this.editedSheet) { this.editedSheet.ResetMap(false); List <int> indexes = this.editedSheet.GetMissingSpriteIndexes(); if (null != indexes) { this.popup = UnityNoticePopup.OpenWindow(string.Format("Found missing sprites!:{0}", indexes.Count), "Remove the missing sprites?\nThen it is automatically saved.", new string[] { "Yes", "No" }, (choice) => { if (0 == choice) { this.Save(this.editedSheet); } else { this.editedSheet = null; } this.popup = null; }); return; } } } if (this.popup) { return; } this.CheckSelectedSprites(this.editedSheet); Color colorOrigin = GUI.color; EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(string.Format("Selected Sprites: {0} Item", this.selectedSprites.Count)); GUI.color = 0 < this.duplicatedSprites.Count ? Color.red : colorOrigin; EditorGUILayout.LabelField(string.Format("Duplicated: {0} Item", this.duplicatedSprites.Count)); GUI.color = colorOrigin; EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); bool enableOld = GUI.enabled; GUI.enabled = 0 < this.availableSprites.Count; GUI.color = !GUI.enabled ? colorOrigin : this.editedSheet ? Color.green : Color.cyan; EditorGUILayout.LabelField(string.Format("Available Sprites: {0} Item", this.availableSprites.Count)); if (this.editedSheet) { if (GUILayout.Button("Add Sprites")) { this.PushAvailableSprites(this.editedSheet); } } else { if (GUILayout.Button("Create Sprite Sheet")) { string path = EditorUtility.SaveFilePanelInProject("Create Sprite Sheet", "sheet.prefab", "prefab", "Please enter a file name to save the sprite sheet to"); if (!string.IsNullOrEmpty(path)) { this.editedSheet = ScriptableObject.CreateInstance(typeof(SpriteSheet)) as SpriteSheet; this.PushAvailableSprites(this.editedSheet); AssetDatabase.CreateAsset(this.editedSheet, AssetDatabase.GenerateUniqueAssetPath(path)); AssetDatabase.Refresh(); this.Repaint(); Selection.activeObject = this.editedSheet; return; } } } GUI.color = colorOrigin; GUI.enabled = enableOld; EditorGUILayout.EndHorizontal(); if (!this.editedSheet) { EditorGUILayout.LabelField("Sprite Sheet is empty."); return; } EditorGUILayout.LabelField(string.Format("Contain Sprites: {0} Item", this.editedSheet.Sprites.Count)); this.scroll = EditorGUILayout.BeginScrollView(this.scroll); Sprite lookAt = null; bool isRemoved = false; this.sortedSprites.Clear(); foreach (Sprite s in this.editedSheet.Sprites) { this.sortedSprites.Add(s); } this.sortedSprites.Sort((l, r) => { return(l.name.CompareTo(r.name)); }); for (int n = 0; n < this.sortedSprites.Count; ++n) { Sprite s = this.sortedSprites[n]; EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(s.name); if (GUILayout.Button("Look At")) { lookAt = s; } if (GUILayout.Button("Remove")) { this.editedSheet.Sprites.Remove(s); isRemoved = true; } EditorGUILayout.EndHorizontal(); } EditorGUILayout.EndScrollView(); if (null != lookAt) { EditorUtility.FocusProjectWindow(); Selection.activeObject = lookAt; } if (isRemoved) { this.Save(this.editedSheet); } }
public static Material NewShaderAndMaterial(string path, string name, string[] keywords = null) { string shaderPath = AssetDatabase.GenerateUniqueAssetPath(path + "/MicroSplat.shader"); string shaderBasePath = shaderPath.Replace(".shader", "_Base.shader"); string matPath = AssetDatabase.GenerateUniqueAssetPath(path + "/MicroSplat.mat"); shaderPath = shaderPath.Replace("//", "/"); shaderBasePath = shaderBasePath.Replace("//", "/"); matPath = matPath.Replace("//", "/"); MicroSplatCompiler compiler = new MicroSplatCompiler(); compiler.Init(); if (keywords == null) { keywords = new string[0]; } var pipeline = MicroSplatUtilities.DetectPipeline(); if (pipeline == MicroSplatUtilities.PipelineType.HDPipeline) { System.Array.Resize(ref keywords, keywords.Length + 1); keywords [keywords.Length - 1] = "_MSRENDERLOOP_UNITYHD"; } else if (pipeline == MicroSplatUtilities.PipelineType.UniversalPipeline) { System.Array.Resize(ref keywords, keywords.Length + 1); keywords [keywords.Length - 1] = "_MSRENDERLOOP_UNITYLD"; } string baseName = "Hidden/MicroSplat/" + name + "_Base"; string baseShader = compiler.Compile(keywords, baseName); string regularShader = compiler.Compile(keywords, name, baseName); System.IO.File.WriteAllText(shaderPath, regularShader); System.IO.File.WriteAllText(shaderBasePath, baseShader); if (keywords.Contains("_MESHOVERLAYSPLATS")) { string meshOverlayShader = compiler.Compile(keywords, name, null, true); System.IO.File.WriteAllText(shaderPath.Replace(".shader", "_MeshOverlay.shader"), meshOverlayShader); } AssetDatabase.Refresh(); Shader s = AssetDatabase.LoadAssetAtPath <Shader> (shaderPath); if (s == null) { Debug.LogError("Shader not found at path " + shaderPath); } Material m = new Material(s); AssetDatabase.CreateAsset(m, matPath); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); var kwds = MicroSplatUtilities.FindOrCreateKeywords(m); kwds.keywords = new List <string> (keywords); EditorUtility.SetDirty(kwds); var propData = MicroSplatShaderGUI.FindOrCreatePropTex(m); if (propData != null) { EditorUtility.SetDirty(propData); } return(AssetDatabase.LoadAssetAtPath <Material> (matPath)); }
public void ExportGenericAnim() { var clip = new AnimationClip { frameRate = 30, }; AnimationUtility.SetAnimationClipSettings(clip, new AnimationClipSettings() { loopTime = false, }); var bones = Poses[0].humanoidBones; for (int i = 0; i < bones.Count; i++) { var positionCurveX = new AnimationCurve(); var positionCurveY = new AnimationCurve(); var positionCurveZ = new AnimationCurve(); var rotationCurveX = new AnimationCurve(); var rotationCurveY = new AnimationCurve(); var rotationCurveZ = new AnimationCurve(); var rotationCurveW = new AnimationCurve(); foreach (var p in Poses) { positionCurveX.AddKey(p.Time, p.humanoidBones[i].LocalPosition.x); positionCurveY.AddKey(p.Time, p.humanoidBones[i].LocalPosition.y); positionCurveZ.AddKey(p.Time, p.humanoidBones[i].LocalPosition.z); rotationCurveX.AddKey(p.Time, p.humanoidBones[i].LocalRotation.x); rotationCurveY.AddKey(p.Time, p.humanoidBones[i].LocalRotation.y); rotationCurveZ.AddKey(p.Time, p.humanoidBones[i].LocalRotation.z); rotationCurveW.AddKey(p.Time, p.humanoidBones[i].LocalRotation.w); } //pathは階層 //http://mebiustos.hatenablog.com/entry/2015/09/16/230000 AnimationUtility.SetEditorCurve(clip, new EditorCurveBinding() { path = Poses[0].humanoidBones[i].Name, type = typeof(Transform), propertyName = "m_LocalPosition.x" }, positionCurveX); AnimationUtility.SetEditorCurve(clip, new EditorCurveBinding() { path = Poses[0].humanoidBones[i].Name, type = typeof(Transform), propertyName = "m_LocalPosition.y" }, positionCurveY); AnimationUtility.SetEditorCurve(clip, new EditorCurveBinding() { path = Poses[0].humanoidBones[i].Name, type = typeof(Transform), propertyName = "m_LocalPosition.z" }, positionCurveZ); AnimationUtility.SetEditorCurve(clip, new EditorCurveBinding() { path = Poses[0].humanoidBones[i].Name, type = typeof(Transform), propertyName = "m_LocalRotation.x" }, rotationCurveX); AnimationUtility.SetEditorCurve(clip, new EditorCurveBinding() { path = Poses[0].humanoidBones[i].Name, type = typeof(Transform), propertyName = "m_LocalRotation.y" }, rotationCurveY); AnimationUtility.SetEditorCurve(clip, new EditorCurveBinding() { path = Poses[0].humanoidBones[i].Name, type = typeof(Transform), propertyName = "m_LocalRotation.z" }, rotationCurveZ); AnimationUtility.SetEditorCurve(clip, new EditorCurveBinding() { path = Poses[0].humanoidBones[i].Name, type = typeof(Transform), propertyName = "m_LocalRotation.w" }, rotationCurveW); } clip.EnsureQuaternionContinuity(); string path = AssetDatabase.GenerateUniqueAssetPath( "Assets/Resources/RecordMotion_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + "_Generic.anim"); AssetDatabase.CreateAsset(clip, path); AssetDatabase.SaveAssets(); return; }
private void OnGUI() { // Background ----------------------------------------- GUILayout.Label("Background", EditorStyles.boldLabel); GUILayout.Label("Note: It will have to be scaled/fitted on your own."); EditorGUILayout.Space(); background = (Sprite)EditorGUILayout.ObjectField("Image", background, typeof(Sprite), true); music = (AudioClip)EditorGUILayout.ObjectField("Music", music, typeof(AudioClip), true); EditorGUILayout.Space(); // Enemies ----------------------------------------- numberOfEnemies = Mathf.Max(0, EditorGUILayout.DelayedIntField("Number of enemies:", numberOfEnemies)); while (numberOfEnemies < enemyList.Count) { enemyList.RemoveAt(enemyList.Count - 1); } while (numberOfEnemies > enemyList.Count) { enemyList.Add(null); } scrollPos = EditorGUILayout.BeginScrollView(scrollPos, GUILayout.Width(310), GUILayout.Height(200)); for (int i = 0; i < enemyList.Count; i++) { enemyList[i] = (Enemy)EditorGUILayout.ObjectField(enemyList[i], typeof(Enemy), true); } EditorGUILayout.EndScrollView(); EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.Space(); // Level name ------------------------------------------------ levelName = EditorGUILayout.TextField("Level Name: ", levelName); EditorGUILayout.Space(); if (GUILayout.Button("Make Level!")) { if (levelName == null) { Debug.LogError("Please name the level."); } else { string localPath = "Assets/Scenes/" + levelName + ".unity"; localPath = AssetDatabase.GenerateUniqueAssetPath(localPath); AssetDatabase.CopyAsset("Assets/Scenes/Level1.unity", localPath); Scene scene = EditorSceneManager.OpenScene(localPath); GameObject.Find("BG1").GetComponent <SpriteRenderer>().sprite = background; GameObject.Find("BG2").GetComponent <SpriteRenderer>().sprite = background; GameObject.Find("Music").GetComponent <AudioSource>().clip = music; BattleManager bm = GameObject.FindObjectOfType <BattleManager>(); bm.spawnableEnemies = new List <Enemy>(numberOfEnemies); for (int i = 0; i < numberOfEnemies; i++) { if (enemyList[i] != null) { bm.spawnableEnemies.Add(enemyList[i]); } } EditorSceneManager.MarkSceneDirty(scene); } } }
public static List <TileBase> ConvertToTileSheet(Dictionary <Vector2Int, TileDragAndDropHoverData> sheet) { List <TileBase> result = new List <TileBase>(); string defaultPath = TileDragAndDropManager.GetDefaultTileAssetPath(); // Early out if all objects are already tiles if (sheet.Values.ToList().FindAll(data => data.hoverObject is TileBase).Count == sheet.Values.Count) { foreach (var item in sheet.Values) { result.Add(item.hoverObject as TileBase); } return(result); } UserTileCreationMode userTileCreationMode = UserTileCreationMode.Overwrite; string path = ""; bool multipleTiles = sheet.Count > 1; int i = 0; HashSet <String> uniqueNames = new HashSet <string>(); if (multipleTiles) { bool userInterventionRequired = false; path = EditorUtility.SaveFolderPanel("Generate tiles into folder ", defaultPath, ""); path = FileUtil.GetProjectRelativePath(path); // Check if this will overwrite any existing assets foreach (var item in sheet.Values) { if (item.hoverObject is Sprite sprite) { var name = sprite.name; if (String.IsNullOrEmpty(name) || uniqueNames.Contains(name)) { name = GenerateUniqueNameForNamelessSprite(sprite, uniqueNames, ref i); } uniqueNames.Add(name); var tilePath = FileUtil.CombinePaths(path, String.Format("{0}.{1}", name, k_TileExtension)); if (File.Exists(tilePath)) { userInterventionRequired = true; break; } } } // There are existing tile assets in the folder with names matching the items to be created if (userInterventionRequired) { var option = EditorUtility.DisplayDialogComplex("Overwrite?", String.Format("Assets exist at {0}. Do you wish to overwrite existing assets?", path), "Overwrite", "Create New Copy", "Reuse"); switch (option) { case 0: // Overwrite { userTileCreationMode = UserTileCreationMode.Overwrite; } break; case 1: // Create New Copy { userTileCreationMode = UserTileCreationMode.CreateUnique; } break; case 2: // Reuse { userTileCreationMode = UserTileCreationMode.Reuse; } break; } } } else { // Do not check if this will overwrite new tile as user has explicitly selected the file to save to path = EditorUtility.SaveFilePanelInProject("Generate new tile", sheet.Values.First().hoverObject.name, k_TileExtension, "Generate new tile", defaultPath); } TileDragAndDropManager.SetUserTileAssetPath(path); if (string.IsNullOrEmpty(path)) { return(result); } i = 0; uniqueNames.Clear(); EditorUtility.DisplayProgressBar("Generating Tile Assets (" + i + "/" + sheet.Count + ")", "Generating tiles", 0f); try { MethodInfo createTileMethod = GridPaintActiveTargetsPreferences.GetCreateTileFromPaletteUsingPreferences(); if (createTileMethod == null) { return(null); } foreach (KeyValuePair <Vector2Int, TileDragAndDropHoverData> item in sheet) { TileBase tile; string tilePath = ""; if (item.Value.hoverObject is Sprite sprite) { tile = createTileMethod.Invoke(null, new object[] { sprite }) as TileBase; if (tile == null) { continue; } var name = tile.name; if (String.IsNullOrEmpty(name) || uniqueNames.Contains(name)) { name = GenerateUniqueNameForNamelessSprite(sprite, uniqueNames, ref i); } uniqueNames.Add(name); tilePath = multipleTiles ? FileUtil.CombinePaths(path, String.Format("{0}.{1}", name, k_TileExtension)) : path; // Case 1216101: Fix path slashes for Windows tilePath = FileUtil.NiceWinPath(tilePath); switch (userTileCreationMode) { case UserTileCreationMode.CreateUnique: { if (File.Exists(tilePath)) { tilePath = AssetDatabase.GenerateUniqueAssetPath(tilePath); } AssetDatabase.CreateAsset(tile, tilePath); } break; case UserTileCreationMode.Overwrite: { AssetDatabase.CreateAsset(tile, tilePath); } break; case UserTileCreationMode.Reuse: { if (File.Exists(tilePath)) { tile = AssetDatabase.LoadAssetAtPath <TileBase>(tilePath); } else { AssetDatabase.CreateAsset(tile, tilePath); } } break; } } else { tile = item.Value.hoverObject as TileBase; } EditorUtility.DisplayProgressBar("Generating Tile Assets (" + i + "/" + sheet.Count + ")", "Generating " + tilePath, (float)i++ / sheet.Count); result.Add(tile); } } finally { EditorUtility.ClearProgressBar(); } AssetDatabase.Refresh(); return(result); }
public static void CreateJMaterial() { var material = new JMaterial(); AssetDatabase.CreateAsset(material, AssetDatabase.GenerateUniqueAssetPath("Assets/JMaterial.asset")); }
public static ScriptableObject CreateScriptableObject(Type type, bool showSaveFilePopup = false, bool selectObject = true) { string path = String.Empty; string typeName = ObjectNames.NicifyVariableName(type.Name); if (showSaveFilePopup) { path = EditorUtility.SaveFilePanelInProject($"Create new {typeName} asset.", $"New {typeName}.asset", "asset", $"Choose a location to save the new {typeName}.", LastAssetSavePath); LastAssetSavePath = path.RemoveExtension(); if (string.IsNullOrEmpty(path)) { return(null); } } else { path = AssetDatabase.GetAssetPath(Selection.activeObject); var name = $"New {typeName}.asset"; var separator = Path.DirectorySeparatorChar; if (path == "") { path = "Assets" + separator + name; } else { if (Directory.Exists(path)) { path += separator; } else { path = path.Substring(0, path.Length - Path.GetFileName(path).Length); } path += name; } } var savedObject = ScriptableObject.CreateInstance(type); var savePath = AssetDatabase.GenerateUniqueAssetPath(path); AssetDatabase.CreateAsset(savedObject, savePath); AssetDatabase.SaveAssets(); if (selectObject) { Selection.activeObject = savedObject; } else { EditorGUIUtility.PingObject(savedObject); } Undo.RegisterCreatedObjectUndo(savedObject, $"Creating {typeName}."); return(savedObject); }
private void OnGUI() { EditorGUILayout.BeginHorizontal(); EditorGUILayout.Space(); // EditorGUILayout.LabelField("Edit Custom Player", mystyle); EditorGUILayout.Space(); EditorGUILayout.EndHorizontal(); playerScriptable = (PlayerScriptable)EditorGUILayout.ObjectField("Scriptable Player", playerScriptable, typeof(PlayerScriptable), false); EditSelectedPlayer(); if (playerScriptable != null) { EditorGUILayout.Space(); playerScriptable.name = EditorGUILayout.TextField("Name", playerScriptable.name); playerScriptable.Life = EditorGUILayout.FloatField("Life", playerScriptable.Life); playerScriptable.speed = EditorGUILayout.FloatField("Speed", playerScriptable.speed); EditorGUILayout.Space(); playerScriptable.VerticalMovement = EditorGUILayout.Toggle("Vertical Movement", playerScriptable.VerticalMovement); playerScriptable.HorizontalMovement = EditorGUILayout.Toggle("Horizontal Movement", playerScriptable.HorizontalMovement); playerScriptable.MeleAttack = EditorGUILayout.Toggle("Melee Attack", playerScriptable.MeleAttack); playerScriptable.RangeAttack = EditorGUILayout.Toggle("Range Attack", playerScriptable.RangeAttack); if (!playerScriptable.VerticalMovement) { playerScriptable.CanJump = EditorGUILayout.Toggle("Can Jump", playerScriptable.CanJump); if (playerScriptable.CanJump) { playerScriptable.jumpForce = EditorGUILayout.FloatField("Jump Force", playerScriptable.jumpForce); } } deadIndex = EditorGUILayout.Popup("Death Types", deadIndex, DeathType); playerScriptable.currentDeath = deadIndex; EditorUtility.SetDirty(playerScriptable); //para que se guarde los cambios if (GUILayout.Button("Create Scriptable Player")) { var scriptable = CreateInstance <PlayerScriptable>(); if (!AssetDatabase.IsValidFolder("Assets/Resources/Data")) { AssetDatabase.CreateFolder("Assets/Resources", "Data"); Debug.Log("The introduced folder doesn't exist, so I just created a default one for you."); AssetDatabase.Refresh(); } var path = "Assets/Resources/Data/" + playerScriptable.name + ".asset"; path = AssetDatabase.GenerateUniqueAssetPath(path); AssetDatabase.CreateAsset(scriptable, path); Save(); } if (GUILayout.Button("Save as Player Prefab")) { var myObject = GameObject.CreatePrimitive(PrimitiveType.Cube); var script = myObject.AddComponent <Player>(); script.data = playerScriptable; string path = "Assets/Resources/Prefabs/" + playerScriptable.name + ".prefab"; Debug.Log("the prefab was saved in " + path); PrefabUtility.SaveAsPrefabAssetAndConnect(myObject, path, InteractionMode.AutomatedAction); Save(); } } else { if (GUILayout.Button("Create New Scriptable Player")) { EditNewPlayer(); } } }
static void CreateAutoMaterial() { var targetTex = Selection.activeObject as Texture2D; if (targetTex == null) { return; } string baseName; if (DeterminePBRTextureType(targetTex.name, out baseName) == PBRTextureType.Undefined) { Debug.LogWarning("Can not determine texture type.", targetTex); return; } var basePath = Path.GetDirectoryName(Application.dataPath) + '/'; var targetDirectoryPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(targetTex)); var path = basePath + targetDirectoryPath; var texPaths = Directory.GetFiles(path).Where(s => !s.EndsWith(".meta")).Select(s => s.Replace(basePath, "")).ToArray(); var texDict = new Dictionary <PBRTextureType, Texture2D>(); foreach (var texPath in texPaths) { var tex = AssetDatabase.LoadAssetAtPath <Texture2D>(texPath); if (tex == null) { continue; } string baseName2; var texType = DeterminePBRTextureType(tex.name, out baseName2); if (baseName != baseName2) { continue; } texDict[texType] = tex; } var shaderName = "Standard"; if (texDict.ContainsKey(PBRTextureType.Roughness)) { shaderName = "Autodesk Interactive"; } else if (texDict.ContainsKey(PBRTextureType.Specular)) { shaderName = "Standard (Specular setup)"; } var shader = Shader.Find(shaderName); var material = new Material(shader); foreach (var pair in texDict) { switch (pair.Key) { case PBRTextureType.Diffuse: material.SetTexture("_MainTex", pair.Value); break; case PBRTextureType.Normal: material.SetTexture("_BumpMap", pair.Value); material.EnableKeyword("_NORMALMAP"); break; case PBRTextureType.Metalic: material.SetTexture("_MetallicGlossMap", pair.Value); material.EnableKeyword("_METALLICGLOSSMAP"); break; case PBRTextureType.Specular: case PBRTextureType.Roughness: material.SetTexture("_SpecGlossMap", pair.Value); material.EnableKeyword("_SPECGLOSSMAP"); break; case PBRTextureType.Height: material.SetTexture("_ParallaxMap", pair.Value); material.EnableKeyword("_PARALLAXMAP"); break; case PBRTextureType.Occlusion: material.SetTexture("_OcclusionMap", pair.Value); break; } } var matPath = targetDirectoryPath + '/' + baseName.Trim('_', '-') + ".mat"; matPath = AssetDatabase.GenerateUniqueAssetPath(matPath); AssetDatabase.CreateAsset(material, matPath); AssetDatabase.ImportAsset(matPath); }
void DrawMaterialEditor() { // Upgrade int numAltMaterials = 0; foreach (var v in SpriteCollection.altMaterials) { if (v != null) { numAltMaterials++; } } if ((SpriteCollection.altMaterials.Length == 0 || numAltMaterials == 0) && SpriteCollection.atlasMaterials.Length != 0) { SpriteCollection.altMaterials = new Material[1] { SpriteCollection.atlasMaterials[0] } } ; if (SpriteCollection.altMaterials.Length > 0) { GUILayout.BeginHorizontal(); bool displayMaterialFoldout = EditorGUILayout.Foldout(true, "Materials"); GUILayout.FlexibleSpace(); if (GUILayout.Button("+", EditorStyles.miniButton)) { Material source = null; int i; for (i = 0; i < SpriteCollection.altMaterials.Length; ++i) { if (SpriteCollection.altMaterials[i] != null) { source = SpriteCollection.altMaterials[i]; break; } } for (i = 0; i < SpriteCollection.altMaterials.Length; ++i) { if (SpriteCollection.altMaterials[i] == null) { break; } } if (i == SpriteCollection.altMaterials.Length) { System.Array.Resize(ref SpriteCollection.altMaterials, SpriteCollection.altMaterials.Length + 1); } Material mtl; if (source == null) { mtl = new Material(Shader.Find(SpriteCollection.premultipliedAlpha?"tk2d/PremulVertexColor":"tk2d/BlendVertexColor")); string assetPath = SpriteCollection.GetAssetPath(); string dirName = System.IO.Path.GetDirectoryName(assetPath); string fileName = System.IO.Path.GetFileNameWithoutExtension(assetPath); string targetPath = dirName + "/" + fileName + " AltMaterial.mat"; targetPath = AssetDatabase.GenerateUniqueAssetPath(targetPath); AssetDatabase.CreateAsset(mtl, targetPath); AssetDatabase.SaveAssets(); mtl = AssetDatabase.LoadAssetAtPath(targetPath, typeof(Material)) as Material; } else { string sourcePath = AssetDatabase.GetAssetPath(source); string targetPath = AssetDatabase.GenerateUniqueAssetPath(sourcePath); AssetDatabase.CopyAsset(sourcePath, targetPath); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); mtl = AssetDatabase.LoadAssetAtPath(targetPath, typeof(Material)) as Material; } SpriteCollection.altMaterials[i] = mtl; SpriteCollection.Trim(); } GUILayout.EndHorizontal(); if (displayMaterialFoldout && SpriteCollection.altMaterials != null) { EditorGUI.indentLevel++; for (int i = 0; i < SpriteCollection.altMaterials.Length; ++i) { if (SpriteCollection.altMaterials[i] == null) { continue; } bool deleteMaterial = false; Material newMaterial = EditorGUILayout.ObjectField(SpriteCollection.altMaterials[i], typeof(Material), false) as Material; if (newMaterial == null) { // Can't delete the last one if (numAltMaterials > 1) { bool inUse = false; foreach (var v in SpriteCollection.textureParams) { if (v.materialId == i) { inUse = true; break; } } if (inUse) { if (EditorUtility.DisplayDialog("Delete material", "This material is in use. Deleting it will reset materials on " + "sprites that use this material.\n" + "Do you wish to proceed?", "Yes", "Cancel")) { deleteMaterial = true; } } else { deleteMaterial = true; } } } else { SpriteCollection.altMaterials[i] = newMaterial; } if (deleteMaterial) { SpriteCollection.altMaterials[i] = null; // fix up all existing materials int targetMaterialId; for (targetMaterialId = 0; targetMaterialId < SpriteCollection.altMaterials.Length; ++targetMaterialId) { if (SpriteCollection.altMaterials[targetMaterialId] != null) { break; } } foreach (var sprite in SpriteCollection.textureParams) { if (sprite.materialId == i) { sprite.materialId = targetMaterialId; } } SpriteCollection.Trim(); } } EditorGUI.indentLevel--; } } }
private GameObject ConvertAvatarTo3(GameObject avatarPrefab2, VRCAvatarDescripterDeserializedObject avatar2Info) { var avatarObj3 = PrefabUtility.InstantiatePrefab(avatarPrefab2) as GameObject; avatarObj3.name = GameObjectUtility.GetUniqueNameForSibling(avatarObj3.transform.parent, $"{ avatarObj3.name}_3.0"); var avatar = avatarObj3.AddComponent <VRCAvatarDescriptor>(); avatar.Name = avatar2Info.Name; avatar.ViewPosition = avatar2Info.ViewPosition; avatar.ScaleIPD = avatar2Info.ScaleIPD; avatar.lipSync = avatar2Info.lipSync; avatar.VisemeSkinnedMesh = avatarObj3.transform.Find(avatar2Info.faceMeshRendererPath)?.GetComponent <SkinnedMeshRenderer>() ?? null; avatar.VisemeBlendShapes = avatar2Info.VisemeBlendShapes; avatar.enableEyeLook = true; avatar.customEyeLookSettings = new VRCAvatarDescriptor.CustomEyeLookSettings { leftEye = avatarObj3.transform.Find(LEFT_EYE_PATH), rightEye = avatarObj3.transform.Find(RIGHT_EYE_PATH), // TODO: 設定が未完了なのでアバターが鏡に写らなくなってしまう //eyelidType = VRCAvatarDescriptor.EyelidType.Blendshapes, eyelidsSkinnedMesh = avatarObj3.transform.Find(EYELIDS_MESH_PATH)?.GetComponent <SkinnedMeshRenderer>() ?? null }; if (avatar.customEyeLookSettings.eyelidsSkinnedMesh is null) { avatar.customEyeLookSettings.eyelidType = VRCAvatarDescriptor.EyelidType.None; } if (avatar.customEyeLookSettings.leftEye is null && avatar.customEyeLookSettings.rightEye is null && avatar.customEyeLookSettings.eyelidType == VRCAvatarDescriptor.EyelidType.None) { avatar.enableEyeLook = false; } avatar.customizeAnimationLayers = true; avatar.baseAnimationLayers = new VRCAvatarDescriptor.CustomAnimLayer[] { new VRCAvatarDescriptor.CustomAnimLayer { type = VRCAvatarDescriptor.AnimLayerType.Base, isDefault = true }, new VRCAvatarDescriptor.CustomAnimLayer { type = VRCAvatarDescriptor.AnimLayerType.Additive, isDefault = true }, new VRCAvatarDescriptor.CustomAnimLayer { type = VRCAvatarDescriptor.AnimLayerType.Gesture, isDefault = true }, new VRCAvatarDescriptor.CustomAnimLayer { type = VRCAvatarDescriptor.AnimLayerType.Action, isDefault = true }, new VRCAvatarDescriptor.CustomAnimLayer { type = VRCAvatarDescriptor.AnimLayerType.FX, isDefault = true } }; avatar.specialAnimationLayers = new VRCAvatarDescriptor.CustomAnimLayer[] { new VRCAvatarDescriptor.CustomAnimLayer { type = VRCAvatarDescriptor.AnimLayerType.Sitting, isDefault = true }, new VRCAvatarDescriptor.CustomAnimLayer { type = VRCAvatarDescriptor.AnimLayerType.TPose, isDefault = true }, new VRCAvatarDescriptor.CustomAnimLayer { type = VRCAvatarDescriptor.AnimLayerType.IKPose, isDefault = true } }; // FaceEmotion var originalHandLayerControllerPath = GetAssetPathForSearch("vrc_AvatarV3HandsLayer t:AnimatorController"); var fxController = DuplicateAnimationLayerController( originalHandLayerControllerPath, Path.GetDirectoryName(avatar2Info.standingOverrideControllerPath), avatarPrefab2.name); avatar.baseAnimationLayers[(int)AnimationLayerType.FX].isDefault = false; avatar.baseAnimationLayers[(int)AnimationLayerType.FX].isEnabled = true; avatar.baseAnimationLayers[(int)AnimationLayerType.FX].animatorController = fxController; avatar.baseAnimationLayers[(int)AnimationLayerType.FX].mask = null; foreach (var layer in fxController.layers) { if (layer.name != "Left Hand" && layer.name != "Right Hand") { continue; } for (int i = 0; i < avatar2Info.OverrideAnimationClips.Length; i++) { var animationInfo = avatar2Info.OverrideAnimationClips[i]; if (animationInfo is null || string.IsNullOrEmpty(animationInfo.Path) || animationInfo.Type.StartsWith("Emote")) { continue; } var animClip = AssetDatabase.LoadAssetAtPath(animationInfo.Path, typeof(AnimationClip)) as AnimationClip; var state = GetAnimatorStateFromStateName(layer.stateMachine, animationInfo.Type); if (state is null) { continue; } state.motion = animClip; } } if (HasEmoteAnimation(avatar2Info.OverrideAnimationClips)) { // Emote var originalActionLayerController = Resources.Load <AnimatorController>("Controllers/vrc_AvatarV3ActionLayer_VRCAV3T"); var originalActionLayerControllerPath = AssetDatabase.GetAssetPath(originalActionLayerController); var actionController = DuplicateAnimationLayerController( originalActionLayerControllerPath, Path.GetDirectoryName(avatar2Info.standingOverrideControllerPath), avatarPrefab2.name); avatar.baseAnimationLayers[(int)AnimationLayerType.Action].isDefault = false; avatar.baseAnimationLayers[(int)AnimationLayerType.Action].isEnabled = true; avatar.baseAnimationLayers[(int)AnimationLayerType.Action].animatorController = actionController; avatar.baseAnimationLayers[(int)AnimationLayerType.Action].mask = null; var actionLayer = actionController.layers[0]; for (int i = 0; i < avatar2Info.OverrideAnimationClips.Length; i++) { var animationInfo = avatar2Info.OverrideAnimationClips[i]; if (animationInfo is null || string.IsNullOrEmpty(animationInfo.Path) || !animationInfo.Type.StartsWith("Emote")) { continue; } var animClip = AssetDatabase.LoadAssetAtPath(animationInfo.Path, typeof(AnimationClip)) as AnimationClip; var state = GetAnimatorStateFromStateName(actionLayer.stateMachine, animationInfo.Type); if (state is null) { continue; } state.motion = animClip; } avatar.customExpressions = true; var exMenu = CreateInstance <VRCExpressionsMenu>(); AssetDatabase.CreateAsset( exMenu, AssetDatabase.GenerateUniqueAssetPath( Path.Combine( Path.GetDirectoryName(avatar2Info.standingOverrideControllerPath), $"ExMenu_{avatarPrefab2.name}.asset"))); var subMenuEmotes = CreateInstance <VRCExpressionsMenu>(); AssetDatabase.CreateAsset( subMenuEmotes, AssetDatabase.GenerateUniqueAssetPath( Path.Combine( Path.GetDirectoryName(avatar2Info.standingOverrideControllerPath), $"ExMenu_Emotes_{avatarPrefab2.name}.asset"))); var exParameters = CreateInstance <VRCExpressionParameters>(); AssetDatabase.CreateAsset( exParameters, AssetDatabase.GenerateUniqueAssetPath( Path.Combine( Path.GetDirectoryName(avatar2Info.standingOverrideControllerPath), $"ExParams_{avatarPrefab2.name}.asset"))); avatar.expressionsMenu = exMenu; avatar.expressionParameters = exParameters; var emoteIconPath = GetAssetPathForSearch("person_dance t:texture"); var emoteIcon = AssetDatabase.LoadAssetAtPath <Texture2D>(emoteIconPath); exMenu.controls.Add(new VRCExpressionsMenu.Control { name = "Emotes", icon = emoteIcon, type = VRCExpressionsMenu.Control.ControlType.SubMenu, subMenu = subMenuEmotes }); for (int i = 0; i < avatar2Info.OverrideAnimationClips.Length; i++) { var animationInfo = avatar2Info.OverrideAnimationClips[i]; if (animationInfo is null || string.IsNullOrEmpty(animationInfo.Path) || !animationInfo.Type.StartsWith("Emote")) { continue; } subMenuEmotes.controls.Add(new VRCExpressionsMenu.Control { name = Path.GetFileNameWithoutExtension(animationInfo.Path), icon = emoteIcon, type = VRCExpressionsMenu.Control.ControlType.Button, parameter = new VRCExpressionsMenu.Control.Parameter { name = "VRCEmote" }, value = int.Parse(animationInfo.Type.Replace("Emote", string.Empty)) }); } Selection.activeObject = exParameters; } AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); return(avatarObj3); }
public void ExportHumanoidAnim() { var clip = new AnimationClip { frameRate = 30, }; AnimationUtility.SetAnimationClipSettings(clip, new AnimationClipSettings() { loopTime = false, }); // position { var curveX = new AnimationCurve(); var curveY = new AnimationCurve(); var curveZ = new AnimationCurve(); foreach (var item in Poses) { curveX.AddKey(item.Time, item.BodyPosition.x); curveY.AddKey(item.Time, item.BodyPosition.y); curveZ.AddKey(item.Time, item.BodyPosition.z); } const string muscleX = "RootT.x"; clip.SetCurve("", typeof(Animator), muscleX, curveX); const string muscleY = "RootT.y"; clip.SetCurve("", typeof(Animator), muscleY, curveY); const string muscleZ = "RootT.z"; clip.SetCurve("", typeof(Animator), muscleZ, curveZ); } // rotation { var curveX = new AnimationCurve(); var curveY = new AnimationCurve(); var curveZ = new AnimationCurve(); var curveW = new AnimationCurve(); foreach (var item in Poses) { curveX.AddKey(item.Time, item.BodyRotation.x); curveY.AddKey(item.Time, item.BodyRotation.y); curveZ.AddKey(item.Time, item.BodyRotation.z); curveW.AddKey(item.Time, item.BodyRotation.w); } const string muscleX = "RootQ.x"; clip.SetCurve("", typeof(Animator), muscleX, curveX); const string muscleY = "RootQ.y"; clip.SetCurve("", typeof(Animator), muscleY, curveY); const string muscleZ = "RootQ.z"; clip.SetCurve("", typeof(Animator), muscleZ, curveZ); const string muscleW = "RootQ.w"; clip.SetCurve("", typeof(Animator), muscleW, curveW); } // muscles for (int i = 0; i < HumanTrait.MuscleCount; ++i) { var curve = new AnimationCurve(); foreach (var item in Poses) { curve.AddKey(item.Time, item.Muscles[i]); } var muscle = HumanTrait.MuscleName[i]; if (MotionDataSettings.TraitPropMap.ContainsKey(muscle)) { muscle = MotionDataSettings.TraitPropMap[muscle]; } clip.SetCurve("", typeof(Animator), muscle, curve); } clip.EnsureQuaternionContinuity(); string path = AssetDatabase.GenerateUniqueAssetPath( "Assets/Resources/RecordMotion_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + "_Humanoid.anim"); AssetDatabase.CreateAsset(clip, path); AssetDatabase.SaveAssets(); return; }
//------------------------------------------------ //Function to create quad mesh void OnWizardCreate() { //Create Vertices Vector3[] Vertices = new Vector3[4]; //Create UVs Vector2[] UVs = new Vector2[4]; //Two triangles of quad int[] Triangles = new int[6]; //Assign vertices based on pivot //Bottom-left Vertices[0].x = -AnchorX; Vertices[0].y = -AnchorY; //Bottom-right Vertices[1].x = Vertices[0].x + Width; Vertices[1].y = Vertices[0].y; //Top-left Vertices[2].x = Vertices[0].x; Vertices[2].y = Vertices[0].y + Height; //Top-right Vertices[3].x = Vertices[0].x + Width; Vertices[3].y = Vertices[0].y + Height; //Assign UVs //Bottom-left UVs[0].x = 0.0f; UVs[0].y = 0.0f; //Bottom-right UVs[1].x = 1.0f; UVs[1].y = 0.0f; //Top-left UVs[2].x = 0.0f; UVs[2].y = 1.0f; //Top-right UVs[3].x = 1.0f; UVs[3].y = 1.0f; //Assign triangles Triangles[0] = 3; Triangles[1] = 1; Triangles[2] = 2; Triangles[3] = 2; Triangles[4] = 1; Triangles[5] = 0; //Generate mesh Mesh mesh = new Mesh(); mesh.name = MeshName; mesh.vertices = Vertices; mesh.uv = UVs; mesh.triangles = Triangles; mesh.RecalculateNormals(); //Create asset in database AssetDatabase.CreateAsset(mesh, AssetDatabase.GenerateUniqueAssetPath(AssetFolder + "/" + MeshName) + ".asset"); AssetDatabase.SaveAssets(); //Create plane game object GameObject plane = new GameObject(GameObjectName); MeshFilter meshFilter = (MeshFilter)plane.AddComponent(typeof(MeshFilter)); plane.AddComponent(typeof(MeshRenderer)); //Assign mesh to mesh filter meshFilter.sharedMesh = mesh; mesh.RecalculateBounds(); //Add a box collider component plane.AddComponent(typeof(BoxCollider)); }
void createAndSetupBaker(List <GameObjectFilterInfo> gaws, string pthRoot) { for (int i = gaws.Count - 1; i >= 0; i--) { if (gaws[i].go == null) { gaws.RemoveAt(i); } } if (gaws.Count < 1) { Debug.LogError("No game objects."); return; } if (pthRoot == null || pthRoot == "") { Debug.LogError("Folder for saving created assets was not set."); return; } int numVerts = 0; for (int i = 0; i < gaws.Count; i++) { if (gaws[i].go != null) { numVerts = gaws[i].numVerts; } } GameObject newMeshBaker = null; if (numVerts >= 65535) { newMeshBaker = MB3_MultiMeshBakerEditor.CreateNewMeshBaker(); } else { newMeshBaker = MB3_MeshBakerEditor.CreateNewMeshBaker(); } newMeshBaker.name = ("MeshBaker-" + gaws[0].shaderName + "-LM" + gaws[0].lightmapIndex).ToString().Replace("/", "-"); MB3_TextureBaker tb = newMeshBaker.GetComponent <MB3_TextureBaker>(); MB3_MeshBakerCommon mb = tb.GetComponentInChildren <MB3_MeshBakerCommon>(); tb.GetObjectsToCombine().Clear(); for (int i = 0; i < gaws.Count; i++) { if (gaws[i].go != null) { tb.GetObjectsToCombine().Add(gaws[i].go); } } if (gaws[0].numMaterials > 1) { string pthMat = AssetDatabase.GenerateUniqueAssetPath(pthRoot + newMeshBaker.name + ".asset"); MB3_TextureBakerEditorInternal.CreateCombinedMaterialAssets(tb, pthMat); tb.doMultiMaterial = true; SerializedObject tbr = new SerializedObject(tb); SerializedProperty resultMaterials = tbr.FindProperty("resultMaterials"); MB3_TextureBakerEditorInternal.ConfigureMutiMaterialsFromObjsToCombine(tb, resultMaterials, tbr); } else { string pthMat = AssetDatabase.GenerateUniqueAssetPath(pthRoot + newMeshBaker.name + ".asset"); MB3_TextureBakerEditorInternal.CreateCombinedMaterialAssets(tb, pthMat); } if (gaws[0].isMeshRenderer) { mb.meshCombiner.renderType = MB_RenderType.meshRenderer; } else { mb.meshCombiner.renderType = MB_RenderType.skinnedMeshRenderer; } }
static public void Setup(string testType, string pathFormat, string suffix) { #if UNITY_EDITOR bool currentIgnoreState = LogAssert.ignoreFailingMessages; LogAssert.ignoreFailingMessages = true; var RootFolder = string.Format(pathFormat, testType, suffix); Directory.CreateDirectory(RootFolder); var settings = AddressableAssetSettings.Create(RootFolder + "/Settings", "AddressableAssetSettings.Tests", false, true); settings.MaxConcurrentWebRequests = kMaxWebRequestCount; var group = settings.FindGroup("TestStuff" + suffix); if (group == null) { group = settings.CreateGroup("TestStuff" + suffix, true, false, false, null, typeof(BundledAssetGroupSchema)); } group.GetSchema <BundledAssetGroupSchema>().BundleNaming = BundledAssetGroupSchema.BundleNamingStyle.OnlyHash; settings.DefaultGroup = group; for (int i = 0; i < kPrefabCount; i++) { var guid = CreateAsset(RootFolder + "/test" + i + suffix + ".prefab", "testPrefab" + i); var entry = settings.CreateOrMoveEntry(guid, group, false, false); entry.address = Path.GetFileNameWithoutExtension(entry.AssetPath); entry.SetLabel(GetPrefabLabel(suffix), true, true); entry.SetLabel(GetPrefabAlternatingLabel(suffix, i), true, true); entry.SetLabel(GetPrefabUniqueLabel(suffix, i), true, true); } var texture = new Texture2D(32, 32); var data = ImageConversion.EncodeToPNG(texture); UnityEngine.Object.DestroyImmediate(texture); AssetDatabase.GenerateUniqueAssetPath(RootFolder); var spritePath = RootFolder + "/sprite.png"; File.WriteAllBytes(spritePath, data); AssetDatabase.ImportAsset(spritePath, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate); var spriteGuid = AssetDatabase.AssetPathToGUID(spritePath); var importer = (TextureImporter)AssetImporter.GetAtPath(spritePath); importer.textureType = TextureImporterType.Sprite; importer.spriteImportMode = SpriteImportMode.Multiple; importer.spritesheet = new SpriteMetaData[] { new SpriteMetaData() { name = "topleft", pivot = Vector2.zero, rect = new Rect(0, 0, 16, 16) }, new SpriteMetaData() { name = "botright", pivot = Vector2.zero, rect = new Rect(16, 16, 16, 16) } }; importer.SaveAndReimport(); var spriteEntry = settings.CreateOrMoveEntry(AssetDatabase.AssetPathToGUID(spritePath), group, false, false); spriteEntry.address = "sprite"; var so = ScriptableObject.CreateInstance <UnityEngine.AddressableAssets.Tests.TestObject>(); var sub = ScriptableObject.CreateInstance <UnityEngine.AddressableAssets.Tests.TestObject>(); sub.name = "sub-shown"; var sub2 = ScriptableObject.CreateInstance <UnityEngine.AddressableAssets.Tests.TestObject>(); sub2.hideFlags |= HideFlags.HideInHierarchy; sub2.name = "sub2-hidden"; so.name = "main"; AssetDatabase.CreateAsset(so, RootFolder + "/assetWithSubObjects.asset"); AssetDatabase.AddObjectToAsset(sub, RootFolder + "/assetWithSubObjects.asset"); AssetDatabase.AddObjectToAsset(sub2, RootFolder + "/assetWithSubObjects.asset"); AssetDatabase.ImportAsset(RootFolder + "/assetWithSubObjects.asset", ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate); var assetWithSubObjectsGUID = AssetDatabase.AssetPathToGUID(RootFolder + "/assetWithSubObjects.asset"); string assetRefGuid = CreateAsset(RootFolder + "/testIsReference.prefab", "IsReference"); GameObject go = new GameObject("AssetReferenceBehavior"); AssetReferenceTestBehavior aRefTestBehavior = go.AddComponent <AssetReferenceTestBehavior>(); settings.CreateOrMoveEntry(assetWithSubObjectsGUID, settings.DefaultGroup).address = "assetWithSubObjects"; aRefTestBehavior.Reference = settings.CreateAssetReference(assetRefGuid); aRefTestBehavior.ReferenceWithSubObject = settings.CreateAssetReference(assetWithSubObjectsGUID); aRefTestBehavior.ReferenceWithSubObject.SubObjectName = "sub-shown"; aRefTestBehavior.LabelReference = new AssetLabelReference() { labelString = settings.labelTable.labelNames[0] }; string hasBehaviorPath = RootFolder + "/AssetReferenceBehavior.prefab"; PrefabUtility.SaveAsPrefabAsset(go, hasBehaviorPath); settings.CreateOrMoveEntry(AssetDatabase.AssetPathToGUID(hasBehaviorPath), group, false, false); //AssetDatabase.StopAssetEditing(); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); RunBuilder(settings, testType, suffix); LogAssert.ignoreFailingMessages = currentIgnoreState; #endif }
//----------------------------------------------------------------------------- string GenerateSpriteSheet() { // Generate texture names string[] tmp_texNameAry = new string[tex2DAry.Length]; // Generate texture rects Rect[] tmp_UVAry = new Rect[tex2DAry.Length]; Rect[] tmp_rectAry = new Rect[tex2DAry.Length]; // setup each input texture string inputPath; for (int i = 0; i < tex2DAry.Length; i++) { inputPath = AssetDatabase.GetAssetPath(tex2DAry[i]); ConfigTexture(inputPath); } // Creating a texture in memory // Create a new 1x1 texture ARGB32 (32 bit with alpha) and no mipmaps Texture2D tex2D = new Texture2D(1, 1, TextureFormat.RGBA32, false); tex2D.alphaIsTransparency = true; // The PackTextures function build array of textures into a single spritesheet. // and returns an array of Rect UV value. // which are stored in the AtlasData.UVs member. // Set 4096 as maximun size tmp_UVAry = tex2D.PackTextures(tex2DAry, padding, 4096); for (int i = 0; i < tex2DAry.Length; i++) { // save each sprite rects for auto slice tmp_rectAry[i] = new Rect(tmp_UVAry[i].x * tex2D.width, tmp_UVAry[i].y * tex2D.height, (float)tex2DAry[i].width, (float)tex2DAry[i].height); // setup name for each sprite // filename plus number // Eg: Soldier_7 tmp_texNameAry[i] = spriteSheetName + "_" + i; } if (!Directory.Exists("Assets/Resources")) { // Create Resources folder in Asset Path AssetDatabase.CreateFolder("Assets", "Resources"); } //Generate file name in Asset Path // Eg: Assets/Resources/spritesheet_OOXX.png string assetName = "spritesheet_" + spriteSheetName; string assetPath = AssetDatabase.GenerateUniqueAssetPath("Assets/Resources/" + assetName + ".png"); //convert to PNG and save to hard-drive byte[] bytes = tex2D.EncodeToPNG(); System.IO.File.WriteAllBytes(assetPath, bytes); bytes = null; //Delete generated texture in memory UnityEngine.Object.DestroyImmediate(tex2D); //Import saved png file into Asset AssetDatabase.ImportAsset(assetPath); //Get Imported Texture tex2D = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Texture2D)) as Texture2D; //Configure texture as atlas ConfigSpriteSheet(AssetDatabase.GetAssetPath(tex2D)); DoSlicing(AssetDatabase.GetAssetPath(tex2D), tmp_texNameAry, tmp_rectAry); return(assetName); }
public static Dictionary <Vector2Int, TileBase> ConvertToTileSheet(Dictionary <Vector2Int, Object> sheet) { Dictionary <Vector2Int, TileBase> result = new Dictionary <Vector2Int, TileBase>(); string defaultPath = ProjectBrowser.s_LastInteractedProjectBrowser ? ProjectBrowser.s_LastInteractedProjectBrowser.GetActiveFolderPath() : "Assets"; // Early out if all objects are already tiles if (sheet.Values.ToList().FindAll(obj => obj is TileBase).Count == sheet.Values.Count) { foreach (KeyValuePair <Vector2Int, Object> item in sheet) { result.Add(item.Key, item.Value as TileBase); } return(result); } UserTileCreationMode userTileCreationMode = UserTileCreationMode.Overwrite; string path = ""; bool multipleTiles = sheet.Count > 1; if (multipleTiles) { bool userInterventionRequired = false; path = EditorUtility.SaveFolderPanel("Generate tiles into folder ", defaultPath, ""); path = FileUtil.GetProjectRelativePath(path); // Check if this will overwrite any existing assets foreach (var item in sheet.Values) { if (item is Sprite) { var tilePath = FileUtil.CombinePaths(path, String.Format("{0}.{1}", item.name, k_TileExtension)); if (File.Exists(tilePath)) { userInterventionRequired = true; break; } } } // There are existing tile assets in the folder with names matching the items to be created if (userInterventionRequired) { var option = EditorUtility.DisplayDialogComplex("Overwrite?", String.Format("Assets exist at {0}. Do you wish to overwrite existing assets?", path), "Overwrite", "Create New Copy", "Reuse"); switch (option) { case 0: // Overwrite { userTileCreationMode = UserTileCreationMode.Overwrite; } break; case 1: // Create New Copy { userTileCreationMode = UserTileCreationMode.CreateUnique; } break; case 2: // Reuse { userTileCreationMode = UserTileCreationMode.Reuse; } break; } } } else { // Do not check if this will overwrite new tile as user has explicitly selected the file to save to path = EditorUtility.SaveFilePanelInProject("Generate new tile", sheet.Values.First().name, k_TileExtension, "Generate new tile", defaultPath); } if (string.IsNullOrEmpty(path)) { return(result); } int i = 0; EditorUtility.DisplayProgressBar("Generating Tile Assets (" + i + "/" + sheet.Count + ")", "Generating tiles", 0f); try { MethodInfo createTileMethod = GridPaintActiveTargetsPreferences.GetCreateTileFromPaletteUsingPreferences(); if (createTileMethod == null) { return(null); } foreach (KeyValuePair <Vector2Int, Object> item in sheet) { TileBase tile; string tilePath = ""; if (item.Value is Sprite) { tile = createTileMethod.Invoke(null, new object[] { item.Value as Sprite }) as TileBase; if (tile == null) { continue; } tilePath = multipleTiles ? FileUtil.CombinePaths(path, String.Format("{0}.{1}", tile.name, k_TileExtension)) : path; switch (userTileCreationMode) { case UserTileCreationMode.CreateUnique: { if (File.Exists(tilePath)) { tilePath = AssetDatabase.GenerateUniqueAssetPath(tilePath); } AssetDatabase.CreateAsset(tile, tilePath); } break; case UserTileCreationMode.Overwrite: { AssetDatabase.CreateAsset(tile, tilePath); } break; case UserTileCreationMode.Reuse: { if (File.Exists(tilePath)) { tile = AssetDatabase.LoadAssetAtPath <TileBase>(tilePath); } else { AssetDatabase.CreateAsset(tile, tilePath); } } break; } } else { tile = item.Value as TileBase; } EditorUtility.DisplayProgressBar("Generating Tile Assets (" + i + "/" + sheet.Count + ")", "Generating " + tilePath, (float)i++ / sheet.Count); result.Add(item.Key, tile); } } finally { EditorUtility.ClearProgressBar(); } AssetDatabase.Refresh(); return(result); }
public override void Action(int instanceId, string pathName, string resourceFile) { AssetDatabase.CreateAsset(EditorUtility.InstanceIDToObject(instanceId), AssetDatabase.GenerateUniqueAssetPath(pathName)); }
public void OnEnable() { setupWindow(); // Data dataRoot.Add(new Label("Choose a Enemy:")); objectData = new ObjectField(); objectData.objectType = typeof(Enemy); dataRoot.Add(objectData); objectData.RegisterCallback <ChangeEvent <UnityEngine.Object> >((evt) => { var change = (evt.target as ObjectField).value; enemy = change as Enemy; UpdateBinding(); }); dataRoot.Add(new Spacer(30)); dataRoot.Add(new Label("Name:")); nameTextField = new TextField(); nameTextField.bindingPath = "objectName"; dataRoot.Add(nameTextField); addSlider(ref dataRoot, 20, 100, "Health: ", "health"); addSlider(ref dataRoot, 30, 500, "Walk Speed: ", "walkSpeed"); addSlider(ref dataRoot, 1, 100, "Time Between Each Attack (s): ", "attackTimeInterval"); dataRoot.Add(new Spacer(30)); dataRoot.Add(new Label("Attack Style:")); var attackStyleEnumField = new EnumField(AttackStyles.RangeBased); dataRoot.Add(attackStyleEnumField); attackStyleEnumField.RegisterCallback <ChangeEvent <Enum> >((evt) => { var change = evt.newValue; if (enemy) { enemy.attackStyle = Convert.ToInt32(change); } }); dataRoot.Add(new Spacer(30)); dataRoot.Add(new Label("Weapon:")); var weaponData = new ObjectField(); weaponData.objectType = typeof(Projectile); weaponData.bindingPath = "weapon"; dataRoot.Add(weaponData); // sprites Button newData = new Button(() => { Enemy newEnemy = CreateInstance <Enemy>(); newEnemy.objectName = "Enemy"; var path = "Assets/Resources/Gauntlet/Prefabs/Enemies"; AssetDatabase.CreateAsset(newEnemy, AssetDatabase.GenerateUniqueAssetPath(path + "/Enemy-00.asset")); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); objectData.value = newEnemy; UpdateBinding(); }); newData.text = "New"; spriteRoot.Add(newData); spriteRoot.Add(new Spacer(30)); spriteRoot.Add(new Label("Enemy Sprite:")); objectTileSprite = new ObjectField(); objectTileSprite.objectType = typeof(Sprite); objectTileSprite.bindingPath = "mainSprite"; spriteRoot.Add(objectTileSprite); objectTileSpriteImage = new Image() { style = { width = 100, height = 100, borderLeftWidth = 2, borderRightWidth = 2, borderTopWidth = 2, borderBottomWidth = 2, marginTop = 10, marginBottom = 20, marginLeft = 10, borderColor = Color.gray }, scaleMode = ScaleMode.ScaleToFit }; objectTileSprite.RegisterCallback <ChangeEvent <UnityEngine.Object> >((evt) => { var change = (evt.target as ObjectField).value; if (change) { var sprite = change as Sprite; GauntletLevelEditor.rebindImageTexture(ref objectTileSpriteImage, sprite); } else { objectTileSpriteImage.image = null; } if (objectData.value) { (objectData.value as Enemy).mainSprite = change as Sprite; } Repaint(); parentWindow.rebindPrefabListView(); }); spriteRoot.Add(objectTileSpriteImage); }
public override void OnInspectorGUI() { serializedObject.Update(); EditorGUILayout.PropertyField(m_IsGlobal); if (!m_IsGlobal.boolValue) // Blend radius is not needed for global volumes { EditorGUILayout.PropertyField(m_BlendRadius); } EditorGUILayout.PropertyField(m_Weight); EditorGUILayout.PropertyField(m_Priority); bool assetHasChanged = false; bool showCopy = m_Profile.objectReferenceValue != null; // The layout system sort of break alignement when mixing inspector fields with custom // layouted fields, do the layout manually instead int buttonWidth = showCopy ? 45 : 60; float indentOffset = EditorGUI.indentLevel * 15f; var lineRect = GUILayoutUtility.GetRect(1, EditorGUIUtility.singleLineHeight); var labelRect = new Rect(lineRect.x, lineRect.y, EditorGUIUtility.labelWidth - indentOffset, lineRect.height); var fieldRect = new Rect(labelRect.xMax, lineRect.y, lineRect.width - labelRect.width - buttonWidth * (showCopy ? 2 : 1), lineRect.height); var buttonNewRect = new Rect(fieldRect.xMax, lineRect.y, buttonWidth, lineRect.height); var buttonCopyRect = new Rect(buttonNewRect.xMax, lineRect.y, buttonWidth, lineRect.height); EditorGUI.PrefixLabel(labelRect, EditorUtilities.GetContent("Profile|A reference to a profile asset.")); using (var scope = new EditorGUI.ChangeCheckScope()) { m_Profile.objectReferenceValue = (PostProcessProfile)EditorGUI.ObjectField(fieldRect, m_Profile.objectReferenceValue, typeof(PostProcessProfile), false); assetHasChanged = scope.changed; } if (GUI.Button(buttonNewRect, EditorUtilities.GetContent("New|Create a new profile."), showCopy ? EditorStyles.miniButtonLeft : EditorStyles.miniButton)) { // By default, try to put assets in a folder next to the currently active // scene file. If the user isn't a scene, put them in root instead. var targetName = m_Target.name; var scene = m_Target.gameObject.scene; var asset = ProfileFactory.CreatePostProcessProfile(scene, targetName); m_Profile.objectReferenceValue = asset; assetHasChanged = true; } if (showCopy && GUI.Button(buttonCopyRect, EditorUtilities.GetContent("Clone|Create a new profile and copy the content of the currently assigned profile."), EditorStyles.miniButtonRight)) { // Duplicate the currently assigned profile and save it as a new profile var origin = (PostProcessProfile)m_Profile.objectReferenceValue; var path = AssetDatabase.GetAssetPath(origin); path = AssetDatabase.GenerateUniqueAssetPath(path); var asset = Instantiate(origin); asset.settings.Clear(); AssetDatabase.CreateAsset(asset, path); foreach (var item in origin.settings) { var itemCopy = Instantiate(item); itemCopy.hideFlags = HideFlags.HideInInspector | HideFlags.HideInHierarchy; itemCopy.name = item.name; asset.settings.Add(itemCopy); AssetDatabase.AddObjectToAsset(itemCopy, asset); } AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); m_Profile.objectReferenceValue = asset; assetHasChanged = true; } EditorGUILayout.Space(); if (m_Profile.objectReferenceValue == null) { if (assetHasChanged) { m_EffectList.Clear(); // Asset wasn't null before, do some cleanup } EditorGUILayout.HelpBox("Assign a Post-process Profile to this volume using the \"Asset\" field or create one automatically by clicking the \"New\" button.\nAssets are automatically put in a folder next to your scene file. If you scene hasn't been saved yet they will be created at the root of the Assets folder.", MessageType.Info); } else { if (assetHasChanged) { RefreshEffectListEditor((PostProcessProfile)m_Profile.objectReferenceValue); } m_EffectList.OnGUI(); } serializedObject.ApplyModifiedProperties(); }
static void CreateUIPanelScript(MenuCommand menuCommand) { GameObject context = menuCommand.context as GameObject; string monogameobjectName; string namespaceName; if (context == null) { return; } string name = context.name; int namespaceLength = name.LastIndexOf("_"); if (namespaceLength == name.Length || namespaceLength < 0) { return; } namespaceName = name.Substring(0, namespaceLength); monogameobjectName = name.Substring(namespaceLength + 1); //Create Script string perfabDir = prefabPathPrefix + namespaceName; string scriptDir = scriptPathPrefix + namespaceName; string scriptPath = scriptDir + "/" + monogameobjectName + ".cs"; if (!Directory.Exists(perfabDir)) { Directory.CreateDirectory(perfabDir); } if (!Directory.Exists(scriptDir)) { Directory.CreateDirectory(scriptDir); } File.Copy(TEMPLATEPATH, scriptPath, true); int index = Application.dataPath.LastIndexOf("Assets"); string scriptFullPath = Application.dataPath.Substring(0, index) + scriptPath; string fileContent = System.IO.File.ReadAllText(scriptFullPath); fileContent = fileContent.Replace("#NAMESPACE#", namespaceName); fileContent = fileContent.Replace("#CLASSNAME#", monogameobjectName); System.IO.File.WriteAllText(scriptFullPath, fileContent); AssetDatabase.Refresh(); //Create Prefab, Add Component to Game Object string prefabPath = perfabDir + "/" + name + ".prefab"; // Make sure the file name is unique, in case an existing Prefab has the same name. prefabPath = AssetDatabase.GenerateUniqueAssetPath(prefabPath); GameObject savedGameobject = PrefabUtility.SaveAsPrefabAssetAndConnect(context, prefabPath, InteractionMode.UserAction); ProjectWindowUtil.ShowCreatedAsset(savedGameobject); }
//public bool ReverseNormals; public GameObject Run(Transform transform, bool ReverseNormals, int triangleIndex) { Vector3 CurrentScale = transform.localScale; transform.localScale = Vector3.one; PolygonCollider2D polygonCollider = transform.GetComponent <PolygonCollider2D>(); //for(int path =0;path<polygonCollider.pathCount;path++) //{ int path = 0; bool overwrite = false; MeshedSprite = new GameObject(); Undo.RegisterCreatedObjectUndo(MeshedSprite, "Created Mesh"); mf = MeshedSprite.AddComponent <MeshFilter>(); mr = MeshedSprite.AddComponent <MeshRenderer>(); mesh = new Mesh(); if (!Directory.Exists(Puppet2D_Editor._puppet2DPath + "/Models")) { Directory.CreateDirectory(Puppet2D_Editor._puppet2DPath + "/Models"); } if (AssetDatabase.LoadAssetAtPath(Puppet2D_Editor._puppet2DPath + "/Models/" + transform.name + "_MESH.asset", typeof(Mesh))) { if (EditorUtility.DisplayDialog("Overwrite Asset?", "Do you want to overwrite the current Mesh & Material?", "Yes, Overwrite", "No, Create New Mesh & Material")) { //mf.mesh = AssetDatabase.LoadAssetAtPath(Puppet2D_Editor._puppet2DPath+"/Models/"+transform.name+"_MESH.asset",typeof(Mesh))as Mesh; string meshPath = (Puppet2D_Editor._puppet2DPath + "/Models/" + transform.name + "_MESH.asset"); AssetDatabase.CreateAsset(mesh, meshPath); overwrite = true; } else { string meshPath = AssetDatabase.GenerateUniqueAssetPath(Puppet2D_Editor._puppet2DPath + "/Models/" + transform.name + "_MESH.asset"); AssetDatabase.CreateAsset(mesh, meshPath); } } else { string meshPath = AssetDatabase.GenerateUniqueAssetPath(Puppet2D_Editor._puppet2DPath + "/Models/" + transform.name + "_MESH.asset"); AssetDatabase.CreateAsset(mesh, meshPath); } Vector2[] vertsToCopy = polygonCollider.GetPath(path); CreateMesh(vertsToCopy, transform, triangleIndex); mesh.vertices = finalVertices; mesh.uv = finalUvs; mesh.normals = finalNormals; mesh.triangles = finalTriangles; mesh.RecalculateBounds(); mesh = calculateMeshTangents(mesh); mf.mesh = mesh; results.Clear(); resultsTriIndexes.Clear(); resultsTriIndexesReversed.Clear(); uvs.Clear(); normals.Clear(); if (!Directory.Exists(Puppet2D_Editor._puppet2DPath + "/Models/Materials")) { Directory.CreateDirectory(Puppet2D_Editor._puppet2DPath + "/Models/Materials"); } if (overwrite) { mr.material = AssetDatabase.LoadAssetAtPath(Puppet2D_Editor._puppet2DPath + "/Models/Materials/" + transform.name + "_MAT.mat", typeof(Material)) as Material; } else { Material newMat = new Material(Shader.Find("Unlit/Transparent")); string materialPath = AssetDatabase.GenerateUniqueAssetPath(Puppet2D_Editor._puppet2DPath + "/Models/Materials/" + transform.name + "_MAT.mat"); AssetDatabase.CreateAsset(newMat, materialPath); mr.material = newMat; } MeshedSprite.transform.localScale = CurrentScale; return(MeshedSprite); }
public static Material NewShaderAndMaterial(string path, string name, string[] keywords = null) { // if no branch sampling is specified, go straight to aggressive. Usually defaults are not done this way, but this seems // to make the most sense.. if (!keywords.Contains("_BRANCHSAMPLES")) { System.Array.Resize(ref keywords, keywords.Length + 2); keywords [keywords.Length - 2] = "_BRANCHSAMPLES"; keywords [keywords.Length - 1] = "_BRANCHSAMPLESARG"; } string shaderPath = AssetDatabase.GenerateUniqueAssetPath(path + "/MicroSplat.shader"); string shaderBasePath = shaderPath.Replace(".shader", "_Base.shader"); string matPath = AssetDatabase.GenerateUniqueAssetPath(path + "/MicroSplat.mat"); shaderPath = shaderPath.Replace("//", "/"); shaderBasePath = shaderBasePath.Replace("//", "/"); matPath = matPath.Replace("//", "/"); MicroSplatCompiler compiler = new MicroSplatCompiler(); compiler.Init(); if (keywords == null) { keywords = new string[0]; } var pipeline = MicroSplatUtilities.DetectPipeline(); if (pipeline == MicroSplatUtilities.PipelineType.HDPipeline) { System.Array.Resize(ref keywords, keywords.Length + 1); keywords [keywords.Length - 1] = "_MSRENDERLOOP_UNITYHD"; } else if (pipeline == MicroSplatUtilities.PipelineType.UniversalPipeline) { System.Array.Resize(ref keywords, keywords.Length + 1); keywords [keywords.Length - 1] = "_MSRENDERLOOP_UNITYLD"; } string baseName = "Hidden/MicroSplat/" + name + "_Base"; string baseShader = compiler.Compile(keywords, baseName); string regularShader = compiler.Compile(keywords, name, baseName); System.IO.File.WriteAllText(shaderPath, regularShader); System.IO.File.WriteAllText(shaderBasePath, baseShader); compiler.GenerateAuxShaders(name, shaderPath, new List <string>(keywords)); AssetDatabase.Refresh(); Shader s = AssetDatabase.LoadAssetAtPath <Shader> (shaderPath); if (s == null) { Debug.LogError("Shader not found at path " + shaderPath); } Material m = new Material(s); AssetDatabase.CreateAsset(m, matPath); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); var kwds = MicroSplatUtilities.FindOrCreateKeywords(m); kwds.keywords = new List <string> (keywords); EditorUtility.SetDirty(kwds); var propData = MicroSplatShaderGUI.FindOrCreatePropTex(m); if (propData != null) { EditorUtility.SetDirty(propData); } AssetDatabase.SaveAssets(); return(AssetDatabase.LoadAssetAtPath <Material> (matPath)); }
public static string Process(string path, Texture2D source) { if (path == null) { path = EditorUtility.SaveFolderPanel(SelectFolderTitle, string.Empty, string.Empty); } if (string.IsNullOrEmpty(path)) { return("Target path no defined"); } if (source == null) { return("Source texture not defined"); } var importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(source)) as TextureImporter; if (importer == null || !importer.isReadable) { return("Source texture should be readable"); } // make folder path relative if (path.IndexOf(Application.dataPath) == 0) { path = "Assets" + path.Substring(Application.dataPath.Length); } var gsData = source.GetPixels(); var colData = new Color[gsData.Length]; Color c; float gs; var invDataLength = 1 / (float)gsData.Length; for (int i = 0, iMax = gsData.Length; i < iMax; i++) { if (i % 1000 == 0) { EditorUtility.DisplayProgressBar(Title, "Processing...", i * invDataLength); } c = gsData [i]; colData [i] = new Color(0.5f * c.r - 0.5f * c.b + 0.5f, -0.25f * c.r + 0.5f * c.g - 0.25f * c.b + 0.5f, 0f); gs = 0.25f * c.r + 0.5f * c.g + 0.25f * c.b; gsData [i] = new Color(gs, gs, gs); } EditorUtility.ClearProgressBar(); var tex = new Texture2D(source.width, source.height, TextureFormat.RGB24, false); try { var fileName = AssetDatabase.GenerateUniqueAssetPath(Path.Combine(path, string.Format("{0}.col.png", source.name))); tex.SetPixels(colData); File.WriteAllBytes(fileName, tex.EncodeToPNG()); fileName = AssetDatabase.GenerateUniqueAssetPath(Path.Combine(path, string.Format("{0}.gs.png", source.name))); tex.SetPixels(gsData); File.WriteAllBytes(fileName, tex.EncodeToPNG()); DestroyImmediate(tex); } catch (Exception ex) { DestroyImmediate(tex); return(ex.Message); } AssetDatabase.Refresh(); return(null); }
void OnGUI() { DoContextMenu(); GUILayout.Label("Quick Material", EditorStyles.boldLabel); Rect r = GUILayoutUtility.GetLastRect(); int left = Screen.width - 68; GUILayout.BeginHorizontal(GUILayout.MaxWidth(Screen.width - 74)); GUILayout.BeginVertical(); m_QueuedMaterial = (Material)EditorGUILayout.ObjectField(m_QueuedMaterial, typeof(Material), true); GUILayout.Space(2); if (GUILayout.Button("Apply (Ctrl+Shift+Click)")) { ApplyMaterial(MeshSelection.topInternal, m_QueuedMaterial); } GUI.enabled = editor != null && MeshSelection.selectedFaceCount > 0; if (GUILayout.Button("Match Selection")) { m_QueuedMaterial = EditorMaterialUtility.GetActiveSelection(); } GUI.enabled = true; GUILayout.EndVertical(); GUI.Box(new Rect(left, r.y + r.height + 2, 64, 64), ""); var previewTexture = EditorMaterialUtility.GetPreviewTexture(m_QueuedMaterial); if (previewTexture != null) { GUI.Label(new Rect(left + 2, r.y + r.height + 4, 60, 60), previewTexture); } else { GUI.Box(new Rect(left + 2, r.y + r.height + 4, 60, 60), ""); GUI.Label(new Rect(left + 2, r.height + 28, 120, 32), "None\n(Texture)"); } GUILayout.EndHorizontal(); GUILayout.Space(4); GUI.backgroundColor = PreferenceKeys.proBuilderDarkGray; UI.EditorGUIUtility.DrawSeparator(2); GUI.backgroundColor = Color.white; GUILayout.Label("Material Palette", EditorStyles.boldLabel); EditorGUI.BeginChangeCheck(); m_CurrentPaletteIndex = EditorGUILayout.Popup("", m_CurrentPaletteIndex, m_AvailablePalettes_Str); if (EditorGUI.EndChangeCheck()) { MaterialPalette newPalette = null; // Add a new material palette if (m_CurrentPaletteIndex >= m_AvailablePalettes.Length) { string path = AssetDatabase.GenerateUniqueAssetPath("Assets/Material Palette.asset"); newPalette = FileUtility.LoadRequired <MaterialPalette>(path); EditorGUIUtility.PingObject(newPalette); } else { newPalette = m_AvailablePalettes[m_CurrentPaletteIndex]; } SetMaterialPalette(newPalette); } EditorGUI.BeginChangeCheck(); s_CurrentPalette = (MaterialPalette)EditorGUILayout.ObjectField(s_CurrentPalette, typeof(MaterialPalette), false); if (EditorGUI.EndChangeCheck()) { SetMaterialPalette(s_CurrentPalette); } GUILayout.Space(4); Material[] materials = CurrentPalette; m_ViewScroll = GUILayout.BeginScrollView(m_ViewScroll); for (int i = 0; i < materials.Length; i++) { if (i == 10) { GUILayout.Space(2); GUI.backgroundColor = PreferenceKeys.proBuilderLightGray; UI.EditorGUIUtility.DrawSeparator(1); GUI.backgroundColor = Color.white; GUILayout.Space(2); } GUILayout.BeginHorizontal(); if (i < 10) { if (GUILayout.Button("Alt + " + (i == 9 ? 0 : (i + 1)).ToString(), EditorStyles.miniButton, GUILayout.MaxWidth(58))) { ApplyMaterial(MeshSelection.topInternal, materials[i]); } } else { if (GUILayout.Button("Apply", EditorStyles.miniButtonLeft, GUILayout.MaxWidth(44))) { ApplyMaterial(MeshSelection.topInternal, materials[i]); } GUI.backgroundColor = Color.red; if (GUILayout.Button("", EditorStyles.miniButtonRight, GUILayout.MaxWidth(14))) { Material[] temp = new Material[materials.Length - 1]; System.Array.Copy(materials, 0, temp, 0, materials.Length - 1); materials = temp; SaveUserMaterials(materials); return; } GUI.backgroundColor = Color.white; } EditorGUI.BeginChangeCheck(); materials[i] = (Material)EditorGUILayout.ObjectField(materials[i], typeof(Material), false); if (EditorGUI.EndChangeCheck()) { SaveUserMaterials(materials); } GUILayout.EndHorizontal(); } if (GUILayout.Button("Add")) { Material[] temp = new Material[materials.Length + 1]; System.Array.Copy(materials, 0, temp, 0, materials.Length); materials = temp; SaveUserMaterials(materials); } GUILayout.EndScrollView(); }