static void UpdateCachedSpriteMesh(SpriteMesh spriteMesh) { if (spriteMesh) { string key = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(spriteMesh)); if (spriteMesh.sprite) { SpriteMesh spriteMeshFromSprite = GetSpriteMeshFromSprite(spriteMesh.sprite); if (!spriteMeshFromSprite || spriteMesh == spriteMeshFromSprite) { string value = AssetDatabase.AssetPathToGUID( AssetDatabase.GetAssetPath(SpriteUtility.GetSpriteTexture(spriteMesh.sprite, false))); s_SpriteMeshToTextureCache[key] = value; } else { Debug.LogWarning("Anima2D: SpriteMesh " + spriteMesh.name + " uses the same Sprite as " + spriteMeshFromSprite.name + ". Use only one SpriteMesh per Sprite."); } } else if (s_SpriteMeshToTextureCache.ContainsKey(key)) { s_SpriteMeshToTextureCache.Remove(key); } } }
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.ObjectField(position, property); Texture2D myText = SpriteUtility.GetSpriteTexture((Sprite)property.objectReferenceValue, false); GUI.Label(position, myText); }
static void showPackInfo_Legacy(Sprite _sprite, GUILayoutOption _option) { TextureImporter ti = (TextureImporter)AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_sprite)); ti.spritePackingTag = EditorGUILayout.TextField(ti.spritePackingTag, _option); EditorGUILayout.LabelField("[Packing Tag]", EditorStyles.boldLabel, _option); Texture2D _texture = SpriteUtility.GetSpriteTexture(_sprite, _sprite.packed); if (_texture != null) { if (_sprite.packed) { EditorGUI.DrawTextureTransparent( EditorGUILayout.GetControlRect( new GUILayoutOption[] { _option, GUILayout.MaxHeight(150) }), _texture, ScaleMode.ScaleToFit); } else { string _msg = !string.IsNullOrEmpty(ti.spritePackingTag) ? "You have to build to see a Packed Texture." : "If you set the same [Packing Tag] to sprites used in the map, render speed will be faster."; EditorGUI.HelpBox( EditorGUILayout.GetControlRect( new GUILayoutOption[] { _option, GUILayout.MaxHeight(75) }), _msg, MessageType.Info); } } }
/// <summary> /// <para>Draws a sprite graphic at a specified <see cref="Rect"/>.</para> /// </summary> /// <param name="rect">The <see cref="Rect"/> in which the item is drawn.</param> /// <param name="sprite">The graphic to draw.</param> /// <param name="style">A style used to modify the appearance of a graphic.</param> /// <param name="selected">Whether the graphic should be rendered with a selection tint.</param> /// <remarks> /// <para>This implementation draws a <see cref="Texture2D"/> and crops the boundaries. This may result in /// sprites that are tightly packed to draw artifacts.</para> /// </remarks> public static void DrawSprite(Rect rect, Sprite sprite, CompiledStyleDefinition style = null, bool selected = false) { if (sprite == null || sprite.Equals(null) || Event.current.type != EventType.Repaint) { return; } Texture2D textureIcon = null; Rect textureRect; if (sprite.packed) { textureIcon = SpriteUtility.GetSpriteTexture(sprite, false); } if (textureIcon == null) { textureIcon = sprite.texture; } textureRect = sprite.rect; DrawTexWithCoords(rect, textureIcon, textureRect, style, selected); }
public void InitFromOutline(float detail, float alphaTolerance, bool holeDetection, float tessellation, string undoName) { Clear(undoName); float pixelsPerUnit = SpriteMeshUtils.GetSpritePixelsPerUnit(spriteMesh.sprite); float factor = pixelsPerUnit / spriteMesh.sprite.pixelsPerUnit; Vector2 position = rect.position / factor; Vector2 size = rect.size / factor; Rect l_rect = new Rect(position.x, position.y, size.x, size.y); Texture2D texture = SpriteUtility.GetSpriteTexture(spriteMesh.sprite, false); Rect clampedRect = MathUtils.ClampRect(MathUtils.OrderMinMax(l_rect), new Rect(0f, 0f, texture.width, texture.height)); List <Vector2> l_texcoords; List <IndexedEdge> l_indexedEdges; List <int> l_indices; SpriteMeshUtils.InitFromOutline(texture, clampedRect, detail, alphaTolerance, holeDetection, out l_texcoords, out l_indexedEdges, out l_indices); SpriteMeshUtils.Tessellate(l_texcoords, l_indexedEdges, holes, l_indices, tessellation * 10f); nodes = l_texcoords.ConvertAll(v => Node.Create(l_texcoords.IndexOf(v))); edges = l_indexedEdges.ConvertAll(e => Edge.Create(nodes[e.index1], nodes[e.index2])); m_TexVertices = l_texcoords.ConvertAll(v => v * factor); boneWeights = l_texcoords.ConvertAll(v => BoneWeight.Create()); indices = l_indices; isDirty = true; m_DirtyVertices = true; }
protected virtual void uploadSpriteTextures() { using (new ProfilerSample("Upload Sprite Textures")) { foreach (var spriteFeature in _spriteFeatures) { var tex = spriteFeature.featureData.Query(). Select(d => d.sprite). Where(s => s != null). #if UNITY_EDITOR Select(s => SpriteUtility.GetSpriteTexture(s, getAtlasData: true)). #else Select(s => s.texture). #endif FirstOrDefault(); if (tex != null) { #if UNITY_EDITOR if (!Application.isPlaying) { _spriteTextureBlock.SetTexture(spriteFeature.propertyName, tex); } else #endif { _material.SetTexture(spriteFeature.propertyName, tex); } } } } }
static void SaveSubTextureInfo() { Texture2D altasTexture = SpriteUtility.GetSpriteTexture(spriteList[0], true); string filename = Application.dataPath + "/Resources/" + MapPrefabDef.MapTerrainSprData + ".txt"; StreamWriter sw; FileInfo t = new FileInfo(filename); if (!t.Exists) { //如果此文件不存在则创建 sw = t.CreateText(); } else { //如果此文件存在则打开 t.Delete(); sw = t.CreateText(); } byte[] altasdata = altasTexture.GetRawTextureData(); System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendFormat(" {0}", altasTexture.name); sb.AppendFormat(" {0}", altasTexture.width); sb.AppendFormat(" {0}", altasTexture.height); sb.AppendFormat(" {0}", (int)altasTexture.format); sb.AppendFormat(" {0}", altasdata.Length); sb.AppendFormat(" {0}", altasTexture.mipmapCount); sb.Remove(0, 1); sw.WriteLine(sb.ToString()); List <Vector4> TArray = new List <Vector4>(); for (int i = 0; i < spriteList.Count; i++) { Vector2[] data = SpriteUtility.GetSpriteUVs(spriteList[i], true); Vector2 ms = new Vector2(altasTexture.width, altasTexture.height); //左上 Vector2 p0 = new Vector2(data[0].x * ms.x, data[0].y * ms.y); //右下 Vector2 p1 = new Vector2(data[1].x * ms.x, data[1].y * ms.y); //右上 Vector2 p2 = new Vector2(data[2].x * ms.x, data[2].y * ms.y); //左下 Vector2 p3 = new Vector2(data[3].x * ms.x, data[3].y * ms.y); var sp = p3; var ss = new Vector2(p1.x - p3.x, p0.y - p3.y); Vector4 pos = new Vector4(sp.x / ms.x, sp.y / ms.y, ss.x / ms.x, ss.y / ms.y); sw.WriteLine(spriteList[i].name + " " + pos.x + " " + pos.y + " " + pos.z + " " + pos.w + "\n"); } sw.Close(); //销毁流 sw.Dispose(); AssetDatabase.Refresh(); }
public static void GetSpriteTextureSize(Sprite sprite, ref int width, ref int height) { if (sprite) { Texture2D texture = SpriteUtility.GetSpriteTexture(sprite, false); TextureImporter textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(texture)) as TextureImporter; GetWidthAndHeight(textureImporter, ref width, ref height); } }
static void SaveAltasTexture() { Texture2D altasTexture = SpriteUtility.GetSpriteTexture(spriteList[0], true); byte[] data = altasTexture.GetRawTextureData(); string filename = Application.dataPath + "/Resources/" + MapPrefabDef.MapAtlas + ".bytes"; FileStream file = new FileStream(filename, FileMode.Create); file.Write(data, 0, data.Length); file.Close(); }
public static void PackAlphaAltasToAssetBoundles() { EditorSettings.spritePackerMode = SpritePackerMode.AlwaysOn; Packer.SelectedPolicy = typeof(CustomPackerPolicy).Name; CustomPackerPolicy.forceIOSOpaque = true; Packer.RebuildAtlasCacheIfNeeded(BuildTarget.iOS, true, Packer.Execution.ForceRegroup); List <UnityEngine.Object> objects = new List <UnityEngine.Object>(); foreach (string path in AssetDatabase.FindAssets("t:sprite")) { objects.AddRange(AssetDatabase.LoadAllAssetRepresentationsAtPath(AssetDatabase.GUIDToAssetPath(path))); } Sprite[] sprites = objects.Distinct() .Select(x => x as Sprite) .Where(x => x != null && x.packed) .ToArray(); List <SerializedObject> sos = new List <SerializedObject>(); foreach (Sprite sprite in sprites) { Texture2D atlasTexture; string atlasName; Packer.GetAtlasDataForSprite(sprite, out atlasName, out atlasTexture); if (atlasTexture != null) { SerializedObject so = new SerializedObject(sprite); so.FindProperty("m_RD.textureRect").rectValue = GetAltasTextureRect(sprite, atlasTexture); so.FindProperty("m_RD.texture").objectReferenceValue = atlasTexture; Texture2D alphaTexture = AssetDatabase.LoadAssetAtPath <Texture2D>("Assets/" + AlphaAtlasManager.TEXTURE_ALPHA_ATLAS_PATH + atlasTexture.name + "_alpha.png"); so.FindProperty("m_RD.alphaTexture").objectReferenceValue = alphaTexture; so.ApplyModifiedProperties(); sos.Add(so); } } EditorSettings.spritePackerMode = SpritePackerMode.Disabled; BuildPipeline.BuildAssetBundles(Application.dataPath + "/AssetBundles", BuildAssetBundleOptions.ChunkBasedCompression, BuildTarget.iOS); EditorSettings.spritePackerMode = SpritePackerMode.AlwaysOn; foreach (SerializedObject so in sos) { Sprite sprite = so.targetObject as Sprite; so.FindProperty("m_RD.textureRect").rectValue = sprite.textureRect; so.FindProperty("m_RD.texture").objectReferenceValue = SpriteUtility.GetSpriteTexture(sprite, false); so.FindProperty("m_RD.alphaTexture").objectReferenceValue = null; so.ApplyModifiedProperties(); } AssetDatabase.Refresh(); }
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.PropertyField(position, property, label, true); if (property.objectReferenceValue != null) { var rect = new Rect(position.width - Attribute.width, position.y, Attribute.width, Attribute.height); using (new ZeroIndent()) { if (property.objectReferenceValue as Sprite) { EditorGUI.DrawPreviewTexture(rect, SpriteUtility.GetSpriteTexture((Sprite)property.objectReferenceValue, false)); } else if (property.objectReferenceValue as Texture) { EditorGUI.DrawPreviewTexture(rect, (Texture)property.objectReferenceValue); } } } }
public static void UpdateAssets(SpriteMesh spriteMesh, SpriteMeshData spriteMeshData) { if (spriteMesh && spriteMeshData) { string spriteMeshPath = AssetDatabase.GetAssetPath(spriteMesh); SerializedObject spriteMeshSO = new SerializedObject(spriteMesh); SerializedProperty sharedMeshProp = spriteMeshSO.FindProperty("m_SharedMesh"); SerializedProperty sharedMaterialsProp = spriteMeshSO.FindProperty("m_SharedMaterials"); if (!spriteMesh.sharedMesh) { Mesh mesh = new Mesh(); mesh.hideFlags = HideFlags.HideInHierarchy; AssetDatabase.AddObjectToAsset(mesh, spriteMeshPath); spriteMeshSO.Update(); sharedMeshProp.objectReferenceValue = mesh; spriteMeshSO.ApplyModifiedProperties(); EditorUtility.SetDirty(mesh); } spriteMesh.sharedMesh.name = spriteMesh.name; if (spriteMesh.sharedMaterials.Length == 0) { Material material = new Material(Shader.Find("Sprites/Default")); material.mainTexture = SpriteUtility.GetSpriteTexture(spriteMesh.sprite, false); AssetDatabase.AddObjectToAsset(material, spriteMeshPath); spriteMeshSO.Update(); sharedMaterialsProp.arraySize = 1; sharedMaterialsProp.GetArrayElementAtIndex(0).objectReferenceValue = material; spriteMeshSO.ApplyModifiedProperties(); } for (int i = 0; i < spriteMesh.sharedMaterials.Length; i++) { Material material = spriteMesh.sharedMaterials [i]; if (material) { if (spriteMesh.sprite) { material.mainTexture = SpriteUtility.GetSpriteTexture(spriteMesh.sprite, false); } material.name = spriteMesh.name + "_" + i; material.hideFlags = HideFlags.HideInHierarchy; EditorUtility.SetDirty(material); } } spriteMeshData.hideFlags = HideFlags.HideInHierarchy; EditorUtility.SetDirty(spriteMeshData); int width = 0; int height = 0; GetSpriteTextureSize(spriteMesh.sprite, ref width, ref height); Vector3[] vertices = GetMeshVertices(spriteMesh.sprite, spriteMeshData); Vector2 textureWidthHeightInv = new Vector2(1f / width, 1f / height); Vector2[] uvs = (new List <Vector2>(spriteMeshData.vertices)).ConvertAll(v => Vector2.Scale(v, textureWidthHeightInv)).ToArray(); Vector3[] normals = (new List <Vector3>(vertices)).ConvertAll(v => Vector3.back).ToArray(); BoneWeight[] boneWeightsData = spriteMeshData.boneWeights; if (boneWeightsData.Length != spriteMeshData.vertices.Length) { boneWeightsData = new BoneWeight[spriteMeshData.vertices.Length]; } List <UnityEngine.BoneWeight> boneWeights = new List <UnityEngine.BoneWeight>(boneWeightsData.Length); List <float> verticesOrder = new List <float>(spriteMeshData.vertices.Length); for (int i = 0; i < boneWeightsData.Length; i++) { BoneWeight boneWeight = boneWeightsData[i]; List <KeyValuePair <int, float> > pairs = new List <KeyValuePair <int, float> >(); pairs.Add(new KeyValuePair <int, float>(boneWeight.boneIndex0, boneWeight.weight0)); pairs.Add(new KeyValuePair <int, float>(boneWeight.boneIndex1, boneWeight.weight1)); pairs.Add(new KeyValuePair <int, float>(boneWeight.boneIndex2, boneWeight.weight2)); pairs.Add(new KeyValuePair <int, float>(boneWeight.boneIndex3, boneWeight.weight3)); pairs = pairs.OrderByDescending(s => s.Value).ToList(); UnityEngine.BoneWeight boneWeight2 = new UnityEngine.BoneWeight(); boneWeight2.boneIndex0 = Mathf.Max(0, pairs[0].Key); boneWeight2.boneIndex1 = Mathf.Max(0, pairs[1].Key); boneWeight2.boneIndex2 = Mathf.Max(0, pairs[2].Key); boneWeight2.boneIndex3 = Mathf.Max(0, pairs[3].Key); boneWeight2.weight0 = pairs[0].Value; boneWeight2.weight1 = pairs[1].Value; boneWeight2.weight2 = pairs[2].Value; boneWeight2.weight3 = pairs[3].Value; boneWeights.Add(boneWeight2); float vertexOrder = i; if (spriteMeshData.bindPoses.Length > 0) { vertexOrder = spriteMeshData.bindPoses[boneWeight2.boneIndex0].zOrder * boneWeight2.weight0 + spriteMeshData.bindPoses[boneWeight2.boneIndex1].zOrder * boneWeight2.weight1 + spriteMeshData.bindPoses[boneWeight2.boneIndex2].zOrder * boneWeight2.weight2 + spriteMeshData.bindPoses[boneWeight2.boneIndex3].zOrder * boneWeight2.weight3; } verticesOrder.Add(vertexOrder); } List <WeightedTriangle> weightedTriangles = new List <WeightedTriangle>(spriteMeshData.indices.Length / 3); for (int i = 0; i < spriteMeshData.indices.Length; i += 3) { int p1 = spriteMeshData.indices[i]; int p2 = spriteMeshData.indices[i + 1]; int p3 = spriteMeshData.indices[i + 2]; weightedTriangles.Add(new WeightedTriangle(p1, p2, p3, verticesOrder[p1], verticesOrder[p2], verticesOrder[p3])); } weightedTriangles = weightedTriangles.OrderBy(t => t.weight).ToList(); List <int> indices = new List <int>(spriteMeshData.indices.Length); for (int i = 0; i < weightedTriangles.Count; ++i) { WeightedTriangle t = weightedTriangles[i]; indices.Add(t.p1); indices.Add(t.p2); indices.Add(t.p3); } List <Matrix4x4> bindposes = (new List <BindInfo>(spriteMeshData.bindPoses)).ConvertAll(p => p.bindPose); for (int i = 0; i < bindposes.Count; i++) { Matrix4x4 bindpose = bindposes [i]; bindpose.m23 = 0f; bindposes[i] = bindpose; } spriteMesh.sharedMesh.Clear(); spriteMesh.sharedMesh.vertices = vertices; spriteMesh.sharedMesh.uv = uvs; spriteMesh.sharedMesh.triangles = indices.ToArray(); spriteMesh.sharedMesh.normals = normals; spriteMesh.sharedMesh.boneWeights = boneWeights.ToArray(); spriteMesh.sharedMesh.bindposes = bindposes.ToArray(); spriteMesh.sharedMesh.RecalculateBounds(); RebuildBlendShapes(spriteMesh); } }
public void OnGUI() { if (spriteArray == null) { return; } int columnCount = Mathf.RoundToInt((position.width) / 70) - 2; int x = 0; int y = 0; int current = 0; GUILayout.Label("2D Tile Placer", EditorStyles.boldLabel); EditorGUILayout.BeginHorizontal(); spriteUnit = EditorGUILayout.IntField("Sprite units: ", spriteUnit); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Paint With Collider", GUILayout.Width(150)); makeCollider = EditorGUILayout.Toggle(makeCollider); EditorGUILayout.EndHorizontal(); //GUILayout.BeginVertical(EditorStyles.helpBox); string[] tools = { "Draw", "Erase" }; selectedTool = GUILayout.Toolbar(selectedTool, tools); tileScrollPosition = EditorGUILayout.BeginScrollView(tileScrollPosition, false, true, GUILayout.Width(position.width)); GUILayout.BeginHorizontal(); for (int i = 0; i < spriteArray.Length; i++) { Sprite child = spriteArray[i]; Rect newRect = new Rect(child.rect.x / child.texture.width, child.rect.y / child.texture.height, child.rect.width / child.texture.width, child.rect.height / child.texture.height); aTexture = SpriteUtility.GetSpriteTexture(child, false); // if (GUILayout.Button("", GUILayout.Width(spriteUnit + (spriteUnit * (1 / 16))), GUILayout.Height(spriteUnit + (spriteUnit * (1 / 16))))) { //draw a clickable button if (cmSelectedTile != null && !Event.current.control) { //empty the selected tile list if control isn't held. Allows multiselect of tiles. cmSelectedTile.Clear(); cmCurSprite.Clear(); } cmSelectedTile.Add(current); //Adds clicked on tile to list of selected tiles. cmCurSprite.Add(child); } GUI.DrawTextureWithTexCoords(new Rect(5 + (x * spriteUnit * 1.06f), 4 + (y * spriteUnit * 1.05f), spriteUnit, spriteUnit), child.texture, newRect, true); //GUI.DrawTexture(newRect, spriteArray[i].texture, ScaleMode.StretchToFill, GUILayout.Width(32.0f), GUILayout.Height(32)); //GUILayout.Label(aTexture); if (x < columnCount) { x++; } else { // if we have enough columns to fill the scroll area, reset the column count and start a new line of buttons x = 0; y++; GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); } } EditorGUILayout.EndScrollView(); //GUILayout.EndVertical(); }
public void OnGUI() { var style = new GUIStyle(GUI.skin.button); if (headObject == null) { CreateNewObject(); } if (spriteArray == null) { return; } int columnCount = Mathf.RoundToInt((position.width) / 70) - 2; int x = 0; int y = 0; int current = 0; GUILayout.Label("2D Tile Placer", EditorStyles.boldLabel); if (GUILayout.Button("New sprite list")) { CreateNewObject(); } GUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Current tool state", GUILayout.Width(150)); GUILayout.BeginVertical(EditorStyles.helpBox); if (isActive) { style.normal.textColor = Color.black; GUI.backgroundColor = new Color32(180, 255, 180, 255); if (GUILayout.Button("Active", style)) { isActive = false; } } else { style.normal.textColor = Color.red; if (GUILayout.Button("De-active", style)) { isActive = true; } } GUILayout.EndVertical(); GUILayout.EndHorizontal(); EditorGUILayout.Space(); tag = EditorGUILayout.TagField("Change tags to: ", tag); layer = EditorGUILayout.LayerField("Change layers to: ", layer); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Paint With Collider", GUILayout.Width(150)); makeCollider = EditorGUILayout.Toggle(makeCollider); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); orderInLayer = EditorGUILayout.IntField("Order in layer: ", orderInLayer); EditorGUILayout.EndHorizontal(); string[] tools = { "Draw", "Erase" }; selectedTool = GUILayout.Toolbar(selectedTool, tools); Debug.Log(selectedTool); tileScrollPosition = EditorGUILayout.BeginScrollView(tileScrollPosition, false, true, GUILayout.Width(position.width)); GUILayout.BeginHorizontal(); for (int i = 0; i < spriteArray.Length; i++) { child = spriteArray[i]; newRect = new Rect(child.rect.x / child.texture.width, child.rect.y / child.texture.height, child.rect.width / child.texture.width, child.rect.height / child.texture.height); aTexture = SpriteUtility.GetSpriteTexture(child, false); if (GUILayout.Button("", GUILayout.Width(spriteUnit + 1 + (spriteUnit * (1 / 16))), GUILayout.Height(spriteUnit + 1 + (spriteUnit * (1 / 16))))) { //draw a clickable button if (cmSelectedTile != null && !Event.current.control) { //empty the selected tile list if control isn't held. Allows multiselect of tiles. cmSelectedTile.Clear(); cmCurSprite.Clear(); } cmSelectedTile.Add(current); //Adds clicked on tile to list of selected tiles. clickedTile = true; cmCurSprite.Add(child); } //Displaying the sprite size inside the tool if (spriteUnit < 40) { spriteUnit = 40; } else if (spriteUnit > 80) { spriteUnit = 80; } //Draws the sprites GUI.DrawTextureWithTexCoords(new Rect(5 + (x * spriteUnit * 1.06f), 4 + (y * spriteUnit * 1.05f), spriteUnit, spriteUnit), child.texture, newRect, true); if (x < columnCount) { x++; } else { // if we have enough columns to fill the scroll area, reset the column count and start a new line of buttons x = 0; y++; GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); } //For selected tiles if (cmSelectedTile != null && cmSelectedTile.Contains(current)) { if (cmSelectedColor == null) { cmSelectedColor = new Texture2D(1, 1); cmSelectedColor.alphaIsTransparency = true; cmSelectedColor.filterMode = FilterMode.Point; cmSelectedColor.SetPixel(0, 0, new Color(.5f, .5f, 1f, .5f)); cmSelectedColor.Apply(); } GUI.DrawTexture(new Rect(5 + (x * spriteUnit * 1.06f), 4 + (y * spriteUnit * 1.05f), spriteUnit, spriteUnit), cmSelectedColor, ScaleMode.ScaleToFit, true); } } EditorGUILayout.EndScrollView(); }
public static Dictionary <string, Texture2D> CreateAlphaAtlasTexture() { Dictionary <string, Texture2D> result = new Dictionary <string, Texture2D>(); List <Entry> entries = new List <Entry>(); Material mat = new Material(Shader.Find("Unlit/Transparent")); List <UnityEngine.Object> objects = new List <UnityEngine.Object>(); foreach (string path in AssetDatabase.FindAssets("t:sprite")) { objects.AddRange(AssetDatabase.LoadAllAssetRepresentationsAtPath(AssetDatabase.GUIDToAssetPath(path))); } Sprite[] sprites = objects.Distinct() .Select(x => x as Sprite) .Where(x => x != null && x.packed) .ToArray(); foreach (Sprite sprite in sprites) { string atlasName; Texture2D atlasTexture; Packer.GetAtlasDataForSprite(sprite, out atlasName, out atlasTexture); Texture2D texture = SpriteUtility.GetSpriteTexture(sprite, false); if (atlasTexture != null && texture != null && texture.format == TextureFormat.RGBA32) { entries.Add(new Entry() { sprite = sprite, atlasName = atlasName, texture = texture, atlasTexture = atlasTexture, uvs = SpriteUtility.GetSpriteUVs(sprite, false), atlasUvs = SpriteUtility.GetSpriteUVs(sprite, true), }); } } var atlasGroups = from e in entries group e by e.atlasTexture; foreach (var atlasGroup in atlasGroups) { Texture tex = atlasGroup.Key; RenderTexture rt = RenderTexture.GetTemporary(tex.width, tex.height, 0, RenderTextureFormat.ARGB32); Graphics.SetRenderTarget(rt); GL.Clear(true, true, Color.clear); GL.PushMatrix(); GL.LoadOrtho(); foreach (var entry in atlasGroup) { mat.mainTexture = entry.texture; mat.SetPass(0); GL.Begin(GL.TRIANGLES); var tris = entry.sprite.triangles; foreach (int index in tris) { GL.TexCoord(entry.uvs[index]); GL.Vertex(entry.atlasUvs[index]); } GL.End(); } GL.PopMatrix(); Texture2D tex2 = new Texture2D(tex.width, tex.height, TextureFormat.RGBA32, false); tex2.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0); var colors = tex2.GetPixels32(); int count = colors.Length; Color32[] newColors = new Color32[count]; for (int i = 0; i < count; i++) { byte alpha = colors[i].a; newColors[i] = new Color32(alpha, alpha, alpha, 255); } tex2.SetPixels32(newColors); tex2.Apply(); string texName = tex.name; texName = tex.name.Substring(0, texName.LastIndexOf("-")) + "-fmt32"; result.Add(texName, tex2); RenderTexture.ReleaseTemporary(rt); } return(result); }
public static void Create() { if (Selection.activeGameObject != null) { GameObject o = Selection.activeGameObject; SkinnedMeshRenderer skin = o.GetComponent <SkinnedMeshRenderer>(); SpriteRenderer spriteRenderer = o.GetComponent <SpriteRenderer>(); if (skin == null && spriteRenderer != null) { Sprite thisSprite = spriteRenderer.sprite; SpriteMesh.CreateSpriteMeshAsset(spriteRenderer.transform, thisSprite); Texture2D spriteTexture = SpriteUtility.GetSpriteTexture(spriteRenderer.sprite, false); Material spriteMaterial = new Material(spriteRenderer.sharedMaterial); spriteMaterial.CopyPropertiesFromMaterial(spriteRenderer.sharedMaterial); spriteMaterial.mainTexture = spriteTexture; DestroyImmediate(spriteRenderer); Skin2D skin2D = o.AddComponent <Skin2D>(); skin2D.sprite = thisSprite; skin = o.GetComponent <SkinnedMeshRenderer>(); MeshFilter filter = o.GetComponent <MeshFilter>(); skin.material = spriteMaterial; filter.mesh = (Mesh)Selection.activeObject; if (filter.sharedMesh != null && skin.sharedMesh == null) { skin.sharedMesh = filter.sharedMesh; } Skeleton skeleton = o.transform.root.GetComponent <Skeleton>(); if (skeleton != null) { // Generate the mesh and calculate the weights if the root transform has a skeleton skeleton.CalculateWeights(true); // Debug.Log("Calculated weights for " + o.name); // Try to initialize the parent bone to this skin Bone bone = o.transform.parent.GetComponent <Bone>(); if (bone != null) { Mesh m = skin.sharedMesh.Clone(); List <BoneWeight> weights = m.boneWeights.ToList(); for (int i = 0; i < m.vertices.Length; i++) { BoneWeight bw = weights[i]; bw = bw.SetWeight(bone.index, 1); weights[i] = bw.Clone(); } skin.sharedMesh.boneWeights = weights.ToArray(); EditorUtility.SetDirty(skin.gameObject); if (PrefabUtility.GetPrefabType(skin.gameObject) != PrefabType.None) { AssetDatabase.SaveAssets(); } } } } else { o = new GameObject("Skin2D"); Undo.RegisterCreatedObjectUndo(o, "Create Skin2D"); o.AddComponent <Skin2D> (); } } else { GameObject o = new GameObject("Skin2D"); Undo.RegisterCreatedObjectUndo(o, "Create Skin2D"); o.AddComponent <Skin2D> (); } }
/* * Draw contents of the window. */ public void OnGUI() { try { // Setup the title GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.BeginVertical(); GUILayout.Space(50.0f); if (sprite != null) { Texture tex = SpriteUtility.GetSpriteTexture(sprite, false); GUILayout.Label(tex); GUILayout.Label("Version 1.3", EditorStyles.centeredGreyMiniLabel); } GUILayout.Space(50.0f); GUILayout.EndVertical(); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); // Handle Project path HandleProjectFolderSelector(); if (project != null) { // Check if timestamp changed FileInfo prjFile = new FileInfo(project.folderPath + "/" + ProjectUtils.projectFileName); if (prjFile.Exists && prjFile.LastWriteTimeUtc.ToBinary() != project.sourceTimestamp) { // Some space for (int i = 0; i < 5; i++) { EditorGUILayout.Space(); } // Handle project refresh HandleProjectRefresh(project, prjFile.LastWriteTimeUtc); } // Handle board and root element selection GUILayout.Space(25.0f); if (project.startingBoardIdx != -1) { for (int i = 0; i < 5; i++) { EditorGUILayout.Space(); } // Hint const string selectionHint = "This section is for assigning the starting board, and the starting node for each board."; EditorGUILayout.LabelField(selectionHint, Resources.styles.folderLabelStyle); // Handle Board Selection HandleStartingBoard(project); // Handle Root Node Selection HandleStartingRoot(project); } } } catch (Exception e) { Debug.LogWarning("[Arcweave] Cannot draw plugin settings window: " + e.Message + "\n" + e.StackTrace); } }
void OnGUI() { currentChoice = EditorGUILayout.Popup(currentChoice, enemyStringArray); if (mySprite != null) { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); Texture2D myTexture = SpriteUtility.GetSpriteTexture(mySprite, false); GUILayout.Label(myTexture); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); } mySprite = EditorGUILayout.ObjectField(mySprite, typeof(Sprite), false) as Sprite; myName = EditorGUILayout.TextField("Name: ", myName); myHealth = EditorGUILayout.IntSlider("Health: ", myHealth, 1, 300); myAttack = EditorGUILayout.IntSlider("Attack: ", myAttack, 1, 100); myDefense = EditorGUILayout.IntSlider("Defense: ", myDefense, 1, 100); myAgility = EditorGUILayout.IntSlider("Agility: ", myAgility, 1, 100); myAttackTime = EditorGUILayout.Slider("Attack Time: ", myAttackTime, 1.0f, 20.0f); magicUser = EditorGUILayout.Toggle("Is Magic User", magicUser); if (magicUser) { myMana = EditorGUILayout.IntSlider("Mana: ", myMana, 1, 100); } //use slider for float if (currentChoice == 0) { if (GUILayout.Button("Create")) { CreateEnemy(); } } else { if (GUILayout.Button("Save")) { SaveCurrentEnemy(); } } if (currentChoice != lastChoice) { if (currentChoice == 0) { NewEnemy(); } else { CurrentEnemy(); } lastChoice = currentChoice; } if (nameFlag) { EditorGUILayout.HelpBox("Put in a name dummy", MessageType.Error); } if (nameExists) { EditorGUILayout.HelpBox("Put in a new name dummy", MessageType.Error); } if (spriteFlag) { EditorGUILayout.HelpBox("Put in a sprite dummy", MessageType.Error); } }
private void FindAllEntries(BuildTarget buildTarget, List <SpriteEntry> spriteEntries, List <AtlasEntry> atlasEntries) { var platformString = GetPlatformString(buildTarget); foreach (var guid in AssetDatabase.FindAssets("t:Texture")) { var path = AssetDatabase.GUIDToAssetPath(guid); var importer = AssetImporter.GetAtPath(path) as TextureImporter; if (importer == null) { continue; } // 获取sprite列表 var sprites = AssetDatabase.LoadAllAssetRepresentationsAtPath(path) .Distinct() .OfType <Sprite>() .Where(x => x.packed) .ToArray(); for (var i = 0; i < sprites.Length; ++i) { var sprite = sprites[i]; Texture2D atlasTexture; string atlasName; Packer.GetAtlasDataForSprite(sprite, out atlasName, out atlasTexture); if (atlasTexture != null) { var entry = new SpriteEntry { Path = path, Sprite = sprite, Importer = importer, Texture = SpriteUtility.GetSpriteTexture(sprite, false), AtlasName = atlasName, Uvs = SpriteUtility.GetSpriteUVs(sprite, false), AtlasUvs = SpriteUtility.GetSpriteUVs(sprite, true), AtlasTexture = atlasTexture, }; spriteEntries.Add(entry); } } } // 获取atlas列表 var atlasGroups = from e in spriteEntries group e by e.AtlasTexture; foreach (var atlasGroup in atlasGroups) { var tex = atlasGroup.Key; var texName = tex.name; // 检查是否需要分离alpha通道 var atlasName = string.Empty; var needSeparateAlpha = false; foreach (var spriteEntry in atlasGroup) { var importer = spriteEntry.Importer; atlasName = importer.spritePackingTag; if (!string.IsNullOrEmpty(atlasName)) { var settings = importer.GetPlatformTextureSettings(platformString); var format = settings.format; if (format == TextureImporterFormat.Automatic) { format = importer.GetAutomaticFormat(platformString); } needSeparateAlpha = TextureUtility.IsTransparent(format); } } if (CustomAtlasConfig.ShouldKeepAlpha(atlasName)) { needSeparateAlpha = false; } var entry = new AtlasEntry { Name = texName, Texture = tex, SpriteEntries = atlasGroup.ToList(), NeedSeparateAlpha = needSeparateAlpha, }; atlasEntries.Add(entry); } }