Exemplo n.º 1
0
        public void DoAutomaticSlicing(int minimumSpriteSize, int alignment, Vector2 pivot, AutoSlicingMethod slicingMethod)
        {
            undoSystem.RegisterCompleteObjectUndo(m_RectsCache, "Automatic Slicing");

            if (slicingMethod == AutoSlicingMethod.DeleteAll)
            {
                m_RectsCache.Clear();
            }

            var         textureToUse = GetTextureToSlice();
            List <Rect> frames       = new List <Rect>(InternalSpriteUtility.GenerateAutomaticSpriteRectangles((UnityTexture2D)textureToUse, minimumSpriteSize, 0));

            frames = SortRects(frames);
            int index         = 0;
            int originalCount = m_RectsCache.spriteRects.Count;

            foreach (Rect frame in frames)
            {
                AddSprite(frame, alignment, pivot, slicingMethod, originalCount, ref index);
            }

            selected = null;
            spriteEditor.SetDataModified();
            Repaint();
        }
Exemplo n.º 2
0
        static void Execute()
        {
            if (Selection.objects.Length > 0)
            {
                foreach (var o in Selection.objects)
                {
                    var             texture         = (Texture2D)o;
                    string          selectionPath   = AssetDatabase.GetAssetPath(texture);
                    TextureImporter textureImporter = AssetImporter.GetAtPath(selectionPath) as TextureImporter;
                    //设置参数
                    if (textureImporter != null)
                    {
                        textureImporter.isReadable         = true;
                        textureImporter.textureType        = TextureImporterType.Sprite;
                        textureImporter.spriteImportMode   = SpriteImportMode.Multiple;
                        textureImporter.mipmapEnabled      = false;
                        textureImporter.filterMode         = FilterMode.Point;
                        textureImporter.spritePivot        = new Vector2(.5f, .5f);
                        textureImporter.textureCompression = TextureImporterCompression.Uncompressed;

                        var textureSettings = new TextureImporterSettings();
                        textureImporter.ReadTextureSettings(textureSettings);
                        textureSettings.spriteMeshType = SpriteMeshType.Tight;
                        textureSettings.spriteExtrude  = 0;
                        textureImporter.SetTextureSettings(textureSettings);

                        int    SliceWidth  = 90;
                        int    SliceHeight = 96;
                        Rect[] rects       = InternalSpriteUtility.GenerateGridSpriteRectangles(texture, Vector2.zero,
                                                                                                new Vector2(SliceWidth, SliceHeight), Vector2.zero);
                        var rectsList = new List <Rect>(rects);
                        rectsList = SortRects(rectsList, texture.width);
                        string fileNameNoExtention = Path.GetFileNameWithoutExtension(selectionPath);
                        var    metas   = new List <SpriteMetaData>();
                        int    rectNum = 0;

                        foreach (var rect in rectsList)
                        {
                            Debug.Log("Generate A Rect Meta Data");
                            var meta = new SpriteMetaData();
                            meta.alignment = 9;
                            meta.pivot     = new Vector2(.5f, .5f);
                            meta.rect      = rect;
                            meta.name      = fileNameNoExtention + "_" + rectNum++;
                            metas.Add(meta);
                        }

                        textureImporter.spritesheet = metas.ToArray();
                    }
                    //设置参数
                    AssetDatabase.ImportAsset(selectionPath, ImportAssetOptions.ForceUpdate);
                }
            }
        }
Exemplo n.º 3
0
    public static void GenerateMultiple()
    {
        string path         = EditorUtility.OpenFolderPanel("Sprite Folder", "", "");
        string relativePath = "Assets" + path.Substring(Application.dataPath.Length);

        if (!AssetDatabase.IsValidFolder(relativePath))
        {
            return;
        }

        string[] folders  = new string[] { relativePath };
        string[] textures = AssetDatabase.FindAssets("t:Texture2D", folders);

        for (int i = 0; i < textures.Length; i++)
        {
            TextureImporter importer = (TextureImporter)TextureImporter.GetAtPath(AssetDatabase.GUIDToAssetPath(textures[i]));
            Texture2D       texture  = (Texture2D)AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(textures[i]), typeof(Texture2D));
            importer.textureType        = TextureImporterType.Sprite;
            importer.spriteImportMode   = SpriteImportMode.Multiple;
            importer.isReadable         = true;
            importer.maxTextureSize     = 8192;
            importer.filterMode         = FilterMode.Point;
            importer.textureCompression = TextureImporterCompression.Uncompressed;

            AssetDatabase.Refresh();

            int    minimumSpriteSize = 16;
            int    extrudeSize       = 0;
            Rect[] rects             = InternalSpriteUtility.GenerateAutomaticSpriteRectangles(texture, minimumSpriteSize, extrudeSize);

            string p            = AssetDatabase.GUIDToAssetPath(textures[i]);
            string relative     = p.Replace("Assets/", "");
            string absolutePath = Application.dataPath + "/" + p;

            string filenameNoExtension  = Path.GetFileNameWithoutExtension(absolutePath);
            List <SpriteMetaData> metas = new List <SpriteMetaData>();
            int rectNum = 0;

            foreach (Rect rect in rects)
            {
                SpriteMetaData meta = new SpriteMetaData();
                meta.rect = rect;
                meta.name = filenameNoExtension + "_" + rectNum++;
                Debug.Log(meta.name);
                metas.Add(meta);
            }

            importer.spritesheet = metas.ToArray();
            importer.SaveAndReimport();
            AssetDatabase.Refresh();
        }
    }
Exemplo n.º 4
0
    static void ProcessTexture(string path, bool isAutomatics)
    {
        Rect[]    rects   = null;
        Texture2D texture = AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D;

        if (isAutomatics)
        {
            int minimumSpriteSize = 16;
            int extrudeSize       = 0;
            rects = InternalSpriteUtility.GenerateAutomaticSpriteRectangles(texture, minimumSpriteSize, extrudeSize);
        }
        else
        {
            string[] str       = texture.name.Split('_');
            int      widthNum  = int.Parse(str[str.Length - 2]);
            int      hrightNum = int.Parse(str[str.Length - 1]);
            Vector2  size      = new Vector2();
            size.x = (float)texture.width / widthNum;
            size.y = (float)texture.height / hrightNum;
            rects  = InternalSpriteUtility.GenerateGridSpriteRectangles(texture, Vector2.zero, size, Vector2.zero);
        }

        var rectsList = new List <Rect>(rects);

        rectsList = SortRects(rectsList, texture.width);

        string filenameNoExtension = Path.GetFileNameWithoutExtension(path);
        var    metas   = new List <SpriteMetaData>();
        int    rectNum = 0;

        foreach (Rect rect in rectsList)
        {
            var meta = new SpriteMetaData();
            meta.pivot     = Vector2.down;
            meta.alignment = (int)SpriteAlignment.BottomCenter;
            meta.rect      = rect;
            meta.name      = filenameNoExtension + "_" + rectNum++;
            metas.Add(meta);
        }

        var importer = AssetImporter.GetAtPath(path) as TextureImporter;

        importer.spritesheet = metas.ToArray();
        EditorUtility.SetDirty(importer);
        AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
        AssetDatabase.Refresh();
    }
Exemplo n.º 5
0
        public void DoGridSlicing(Vector2 size, Vector2 offset, Vector2 padding, int alignment, Vector2 pivot)
        {
            UnityEngine.Texture2D readableTexture2D = this.m_TextureDataProvider.GetReadableTexture2D();
            Rect[] array = InternalSpriteUtility.GenerateGridSpriteRectangles(readableTexture2D, offset, size, padding);
            int    num   = 0;

            base.undoSystem.RegisterCompleteObjectUndo(this.m_RectsCache, "Grid Slicing");
            this.m_RectsCache.spriteRects.Clear();
            Rect[] array2 = array;
            for (int i = 0; i < array2.Length; i++)
            {
                Rect rect = array2[i];
                this.AddSprite(rect, alignment, pivot, 254, 0.25f, this.GetSpriteNamePrefix() + "_" + num++);
            }
            base.selected = null;
            base.spriteEditor.SetDataModified();
            base.Repaint();
        }
        public void DoGridSlicing(Vector2 size, Vector2 offset, Vector2 padding, int alignment, Vector2 pivot)
        {
            var textureToUse = GetTextureToSlice();

            Rect[] frames = InternalSpriteUtility.GenerateGridSpriteRectangles((UnityTexture2D)textureToUse, offset, size, padding);

            int index = 0;

            undoSystem.RegisterCompleteObjectUndo(m_RectsCache, "Grid Slicing");
            m_RectsCache.spriteRects.Clear();

            foreach (Rect frame in frames)
            {
                AddSprite(frame, alignment, pivot, kDefaultColliderAlphaCutoff, kDefaultColliderDetail, GetSpriteNamePrefix() + "_" + index++, Vector4.zero);
            }

            selected = null;
            spriteEditor.SetDataModified();
            Repaint();
        }
Exemplo n.º 7
0
    private void GenerateMultiple(Texture2D tex)
    {
        Debug.Log("Generate Multiple: " + tex.name);

        TextureImporter            importer    = (TextureImporter)TextureImporter.GetAtPath(AssetDatabase.GetAssetPath(tex));
        TextureImporterCompression compression = importer.textureCompression;
        bool readable = importer.isReadable;

        importer.isReadable         = true;
        importer.textureCompression = TextureImporterCompression.Uncompressed;
        importer.spriteImportMode   = SpriteImportMode.Multiple;

        importer.SaveAndReimport();
        AssetDatabase.Refresh();

        int minimumSpriteSize = 16;
        int extrudeSize       = 0;

        Rect[] rects = InternalSpriteUtility.GenerateAutomaticSpriteRectangles(tex, minimumSpriteSize, extrudeSize);

        List <SpriteMetaData> metas = new List <SpriteMetaData>();
        int rectNum = 0;

        foreach (Rect r in rects)
        {
            SpriteMetaData meta = new SpriteMetaData();
            meta.rect = r;
            meta.name = tex.name + "_" + rectNum++;
            Debug.Log(meta.name);
            metas.Add(meta);
        }

        importer.spritesheet = metas.ToArray();
        //importer.SaveAndReimport();
        //AssetDatabase.Refresh();

        importer.textureCompression = compression;
        importer.isReadable         = readable;
        importer.SaveAndReimport();
        AssetDatabase.Refresh();
    }
Exemplo n.º 8
0
        public void DoAutomaticSlicing(int minimumSpriteSize, int alignment, Vector2 pivot, SpriteFrameModule.AutoSlicingMethod slicingMethod)
        {
            base.undoSystem.RegisterCompleteObjectUndo(this.m_RectsCache, "Automatic Slicing");
            if (slicingMethod == SpriteFrameModule.AutoSlicingMethod.DeleteAll)
            {
                this.m_RectsCache.spriteRects.Clear();
            }
            UnityEngine.Texture2D readableTexture2D = this.m_TextureDataProvider.GetReadableTexture2D();
            List <Rect>           list = new List <Rect>(InternalSpriteUtility.GenerateAutomaticSpriteRectangles(readableTexture2D, minimumSpriteSize, 0));

            list = this.SortRects(list);
            int num = 0;

            foreach (Rect current in list)
            {
                this.AddSprite(current, alignment, pivot, slicingMethod, ref num);
            }
            base.selected = null;
            base.spriteEditor.SetDataModified();
            base.Repaint();
        }
Exemplo n.º 9
0
        public void DoGridSlicing(Vector2 size, Vector2 offset, Vector2 padding, int alignment, Vector2 pivot, AutoSlicingMethod slicingMethod, bool keepEmptyRects = false)
        {
            var textureToUse = GetTextureToSlice();

            Rect[] frames = InternalSpriteUtility.GenerateGridSpriteRectangles((UnityTexture2D)textureToUse, offset, size, padding, keepEmptyRects);

            int index = 0;

            undoSystem.RegisterCompleteObjectUndo(m_RectsCache, "Grid Slicing");
            if (slicingMethod == AutoSlicingMethod.DeleteAll)
            {
                m_RectsCache.Clear();
            }

            foreach (Rect frame in frames)
            {
                AddSprite(frame, alignment, pivot, slicingMethod, ref index);
            }

            selected = null;
            spriteEditor.SetDataModified();
            Repaint();
        }
    public static List <SpriteMetaData> GetSheetMetas(Texture2D texture, string path)
    {
        var fn = Path.GetFileNameWithoutExtension(path);

        CharaSheetNameParser.ParseName(fn, out string charaName, out string animName, out Vector2 cellSizeV, out Vector2 pivotV, out string cellSize, out string pivot);
        Rect[]      rects       = InternalSpriteUtility.GenerateGridSpriteRectangles(texture, Vector2.zero, cellSizeV, Vector2.zero);
        List <Rect> sortedRects = rects.ToList();

        List <SpriteMetaData> metas = new List <SpriteMetaData>();
        int rectNum = 0;

        foreach (Rect rect in sortedRects)
        {
            SpriteMetaData meta = new SpriteMetaData();
            meta.rect = rect;
            meta.name = fn + "_" + rectNum;
            rectNum++;
            meta.alignment = (int)SpriteAlignment.Custom;
            meta.pivot     = pivotV;
            metas.Add(meta);
        }
        return(metas);
    }
Exemplo n.º 11
0
    public static List <SpriteRect> DoGridSlicing(string path, Vector2 size, Vector2 offset, Vector2 padding, int alignment, Vector2 pivot)
    {
        var textureToUse = GetTextureToSlice(path);

        Rect[] frames = InternalSpriteUtility.GenerateGridSpriteRectangles((UnityTexture2D)textureToUse, offset, size, padding);

        int index = 0;

        List <SpriteRect> spriteRects = new List <SpriteRect>();

        foreach (Rect rect in frames)
        {
            SpriteRect spriteRect = new SpriteRect();

            spriteRect.rect      = rect;
            spriteRect.alignment = (SpriteAlignment)alignment;
            spriteRect.pivot     = pivot;
            // 使用缓存的原图片名字,不使用索引
            if (m_IconDic.ContainsKey(index))
            {
                spriteRect.name = m_IconDic[index];
            }
            else
            {
                spriteRect.name = "Error" + index.ToString();
                Debug.LogError("找不到对应索引图片的名称:" + index.ToString());
            }

            //spriteRect.originalName = spriteRect.name;
            spriteRect.border = Vector4.zero;

            spriteRects.Add(spriteRect);
            ++index;
        }

        return(spriteRects);
    }
Exemplo n.º 12
0
        static SpriteMetaData[] CreateSpriteSheetForTextureBogdan(Texture2D texture, SpriteSlicingOptions slicingOptions)
        {
            Rect[] gridRects = InternalSpriteUtility.GenerateGridSpriteRectangles(texture, Vector2.zero,
                                                                                  slicingOptions.CellSize, Vector2.zero);

            string path     = AssetDatabase.GetAssetPath(texture);
            var    importer = AssetImporter.GetAtPath(path) as TextureImporter;

            var spriteSheet = importer.spritesheet ?? new SpriteMetaData[gridRects.Length];

            // Add new sprite meta data to the end for all the newly parsed grid rects?
            if (importer.spritesheet != null)
            {
                spriteSheet = spriteSheet.Concat(new SpriteMetaData[Mathf.Max(0, gridRects.Length - importer.spritesheet.Length)]).ToArray();
            }

            for (var i = 0; i < spriteSheet.Length; i++)
            {
                bool sliceExists = importer.spritesheet != null && i < importer.spritesheet.Length;
                bool changePivot = !sliceExists || slicingOptions.OverridePivot;
                spriteSheet[i] = new SpriteMetaData
                {
                    alignment = changePivot ? (int)slicingOptions.Pivot: spriteSheet[i].alignment,
                    pivot     = changePivot ? slicingOptions.CustomPivot : spriteSheet[i].pivot,
                    name      = sliceExists ? spriteSheet[i].name : texture.name + "_" + i,
                    rect      = gridRects[i]
                };
            }

            if (slicingOptions.Frames > 0)
            {
                spriteSheet = spriteSheet.Take((int)slicingOptions.Frames).ToArray();
            }

            return(spriteSheet);
        }
Exemplo n.º 13
0
    static void ConvertTextureToSprite(Texture2D texture)
    {
        Debug.Log("Processing Textures -> " + texture.name.ToString() + " " + texture.width + "," + texture.height);


        // Get Texture2D

        // get asset at path
        string path = AssetDatabase.GetAssetPath(texture);
        // create TextureImporter
        var importer = AssetImporter.GetAtPath(path) as TextureImporter;


        // Texture2D / Sprite options

        // setting to false saves memory
        importer.isReadable = true;
        // change to sprite
        importer.textureType = TextureImporterType.Sprite;
        // change to spritesheets
        importer.spriteImportMode = SpriteImportMode.Multiple;
        // point in the Sprite object's coordinate space where the graphic is located
        importer.spritePivot = Vector2.down;


        // performance / visual

        // allow to increase visual quality at small sizes
        importer.mipmapEnabled = false;
        // filter mode, performance (high to low) = point, bi, tri
        // https://forum.unity.com/threads/filter-mode-point-bilinear-trilinear-which-is-the-cheapest.147523/
        importer.filterMode = FilterMode.Point;
        // image compression https://docs.unity3d.com/ScriptReference/TextureImporterCompression.html
        importer.textureCompression = TextureImporterCompression.Uncompressed;


        // Texture2D mesh options

        // spriteExtrude and spriteMeshType aren't exposed on TextureImporter
        // https://docs.unity3d.com/ScriptReference/TextureImporterSettings.html
        var textureImporterSettings = new TextureImporterSettings();

        importer.ReadTextureSettings(textureImporterSettings);
        // set mesh type to full rectangle (original size)
        textureImporterSettings.spriteMeshType = SpriteMeshType.FullRect;
        // number of blank pixels to leave between the edge of the graphic and the mesh.
        textureImporterSettings.spriteExtrude = 0;
        // add texture-specific settings to importer
        importer.SetTextureSettings(textureImporterSettings);



        // Sprite Slice options

        // number animation slices
        int slices = 3;
        // ?
        int extrudeSize = 0;
        // width / height of sprite slices
        // monsters-400h: 500w x 400h
        int sliceW = texture.width / slices;
        int sliceH = texture.height;


        // Create slices

        // generate sprite rects on texture,
        Rect[] rects = InternalSpriteUtility.GenerateAutomaticSpriteRectangles(texture, slices, extrudeSize);
        // get and sort list of rects added
        var rectsList = new List <Rect>(rects);

        rectsList = SortRects(rectsList, texture.width);


        // Save slices

        // get filename
        string filenameNoExtension = Path.GetFileNameWithoutExtension(path);
        // create sprite metadata
        var metas = new List <SpriteMetaData>();
        // the current rect we are adding
        int rectNum = 0;

        // loop through the rects in the sprite
        foreach (Rect rect in rectsList)
        {
            // create meta for individual sprite
            var meta = new SpriteMetaData();
            // set sprite pivot
            meta.pivot = Vector2.down;
            // set sprite alignment
            meta.alignment = (int)SpriteAlignment.BottomCenter;
            // set rect coordinates: X1,Y1 X2,Y2
            meta.rect = new Rect((rectNum * sliceW), 0, sliceW, sliceH);
            // update sprite name
            meta.name = filenameNoExtension + "_" + rectNum++;
            // add to metadata
            metas.Add(meta);

            Debug.Log("Adding sprite slice -> " + meta.name + " -> " + meta);
        }

        Debug.Log("Saving slices -> " + texture.name + " " + metas.ToString());

        importer.spritesheet = metas.ToArray();

        // save changes to AssetDatabase
        AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
    }
        public static void ApplyDefaultTextureSettings()
        {
            if (Prefs == null)
            {
                LoadPrefs();
            }

            foreach (var obj in Selection.objects)
            {
                if (!AssetDatabase.Contains(obj))
                {
                    continue;
                }

                string path = AssetDatabase.GetAssetPath(obj);

                var importer = AssetImporter.GetAtPath(path) as TextureImporter;
                if (importer == null)
                {
                    continue;
                }

                TextureImporterSettings settings = new TextureImporterSettings();

                // Try to slice it first
                var fileName = Path.GetFileNameWithoutExtension(path);
                var size     = GetSize(path, Prefs.SizeDetectionRegex);

                if (size != Vector2.zero)
                {
                    importer.spriteImportMode = SpriteImportMode.Multiple;

                    var gridRects = InternalSpriteUtility.GenerateGridSpriteRectangles(
                        AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D, Vector2.zero, size, Vector2.zero);

                    importer.spritesheet = gridRects
                                           .Select(x => new SpriteMetaData
                    {
                        alignment = (int)Prefs.SpriteAlignment,
                        name      = fileName + "_" + Array.IndexOf(gridRects, x),
                        rect      = x
                    }).ToArray();
                }
                else
                {
                    importer.spriteImportMode = SpriteImportMode.Single;
                }

                importer.ReadTextureSettings(settings);

                settings.filterMode    = Prefs.FilterMode;
                settings.wrapMode      = Prefs.WrapMode;
                settings.mipmapEnabled = Prefs.EnableMipMaps;
                settings.textureFormat = Prefs.TextureFormat;

                settings.spritePixelsPerUnit = Prefs.PixelsPerUnit;
                settings.spriteAlignment     = (int)Prefs.SpriteAlignment;
                settings.spriteExtrude       = Prefs.SpriteExtrude;
                settings.spriteMeshType      = Prefs.SpriteMeshType;

                importer.SetTextureSettings(settings);
                AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
                EditorUtility.SetDirty(obj);
            }
        }
    public static string ProcessTexture(Texture2D texture, Vector2 size, string[] spriteNames = null)
    {
        string path     = AssetDatabase.GetAssetPath(texture);
        var    importer = AssetImporter.GetAtPath(path) as TextureImporter;

        //importer.isReadable = true;
        importer.textureType        = TextureImporterType.Sprite;
        importer.spriteImportMode   = SpriteImportMode.Multiple;
        importer.mipmapEnabled      = false;
        importer.filterMode         = FilterMode.Point;
        importer.spritePivot        = new Vector2(0.5f, 0.5f);
        importer.textureCompression = TextureImporterCompression.Uncompressed;

        var textureSettings = new TextureImporterSettings();

        importer.ReadTextureSettings(textureSettings);
        textureSettings.spriteMeshType = SpriteMeshType.Tight;
        textureSettings.spriteExtrude  = 0;

        importer.SetTextureSettings(textureSettings);

        //int minimumSpriteSize = 32;
        //int extrudeSize = 0;
        //Rect[] rects = InternalSpriteUtility.GenerateAutomaticSpriteRectangles(texture, minimumSpriteSize, extrudeSize);
        Vector2 offset  = Vector2.zero;
        Vector2 padding = Vector2.zero;

        Rect[] rects     = InternalSpriteUtility.GenerateGridSpriteRectangles(texture, offset, size, padding);
        var    rectsList = new List <Rect>(rects);

        rectsList = SortRects(rectsList, texture.width);

        string filenameNoExtension = Path.GetFileNameWithoutExtension(path);
        var    metas   = new List <SpriteMetaData>();
        int    rectNum = 0;

        foreach (Rect rect in rectsList)
        {
            var meta = new SpriteMetaData
            {
                pivot     = new Vector2(0.5f, 0.5f),
                alignment = (int)SpriteAlignment.Center,
                rect      = rect,
            };
            if (null == spriteNames || spriteNames.Length <= 0)
            {
                meta.name = filenameNoExtension + "_" + rectNum;
            }
            else
            {
                meta.name = spriteNames[rectNum];
            }
            rectNum++;
            metas.Add(meta);
        }

        importer.spritesheet = metas.ToArray();

        AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);

        return(path);
    }
Exemplo n.º 16
0
    private static void ImportEditorMaps()
    {
        string path = EditorUtility.OpenFolderPanel("Import Sprite Editor Maps", "", "");

        string[]      mapFolders       = Directory.GetDirectories(path);
        List <string> foldersToProcess = new List <string>();

        // Determin Order of Import
        foreach (string mapFolder in mapFolders)
        {
            string unityFolder = mapFolder + "\\Unity";
            string mapName     = mapFolder.Substring(mapFolder.IndexOf("\\") + 1).Replace(" ", "_");

            if (Directory.Exists(unityFolder))
            {
                if (File.Exists(unityFolder + "\\" + mapName + ".png"))
                {
                    foldersToProcess.Insert(0, unityFolder);
                }
                else
                {
                    foldersToProcess.Add(unityFolder);
                }
            }
        }

        foreach (string unityFolder in foldersToProcess)
        {
            string mapFolder = unityFolder.Replace("\\Unity", "");
            string mapName   = mapFolder.Substring(mapFolder.IndexOf("\\") + 1).Replace(" ", "_");

            MapInfo   mapInfo        = null;
            Sheet     sheet          = null;
            Texture2D texture        = null;
            bool      hasSpriteSheet = false;

            bool needUpdate = ReadJsonFile(unityFolder, mapName, ref texture, ref sheet, ref mapInfo, ref hasSpriteSheet);

            if (needUpdate)
            {
                if (hasSpriteSheet)
                {
                    // Add the image to the assets library
                    texture.name = mapName;
                    var    bytes     = texture.EncodeToPNG();
                    string assetPath = "Assets/Resources/Maps/" + mapName + "/";

                    if (!Directory.Exists(assetPath))
                    {
                        Directory.CreateDirectory(assetPath);
                    }

                    string fileName = assetPath + mapName + ".png";
                    File.WriteAllBytes(fileName, bytes);
                    AssetDatabase.Refresh();
                    AssetDatabase.ImportAsset(fileName);
                    TextureImporter importer = AssetImporter.GetAtPath(fileName) as TextureImporter;
                    if (importer.spriteImportMode == SpriteImportMode.Multiple)
                    {
                        importer.spriteImportMode = SpriteImportMode.Single;
                        AssetDatabase.WriteImportSettingsIfDirty(fileName);
                    }
                    TextureImporterSettings settings = new TextureImporterSettings();
                    importer.ReadTextureSettings(settings);
                    settings.spriteGenerateFallbackPhysicsShape = false;
                    importer.SetTextureSettings(settings);

                    importer.spriteImportMode    = SpriteImportMode.Multiple;
                    importer.textureType         = TextureImporterType.Sprite;
                    importer.spritePixelsPerUnit = sheet.CellWidth;

                    // Build Sprite Sheet
                    Rect[] rects = InternalSpriteUtility.GenerateGridSpriteRectangles(texture, new Vector2(0, 0), new Vector2(sheet.CellWidth, sheet.CellHeight), new Vector2(0, 0), true);

                    var metas   = new List <SpriteMetaData>();
                    int rectNum = 0;

                    foreach (Rect rect in rects)
                    {
                        var meta = new SpriteMetaData();
                        meta.pivot     = Vector2.zero;
                        meta.alignment = (int)SpriteAlignment.Center;
                        meta.rect      = rect;
                        meta.name      = mapName + "_" + rectNum++;
                        metas.Add(meta);
                    }

                    importer.spritesheet = metas.ToArray();

                    AssetDatabase.ImportAsset(fileName, ImportAssetOptions.ForceUpdate);

                    // Set Physics Shapes
                    UnityEngine.Object[] sprites = AssetDatabase.LoadAllAssetsAtPath("Assets/Resources/Maps/" + mapName + "/" + mapName + ".png");

                    for (int i = 0; i < sprites.Length; i++)
                    {
                        Sprite sprite = sprites[i] as Sprite;

                        if (sprite != null)
                        {
                            try
                            {
                                int            idx    = Convert.ToInt32(sprite.name.Substring(sprite.name.LastIndexOf('_') + 1));
                                List <Vector2> points = new List <Vector2>();
                                if (sheet.Masks[idx].Count > 0)
                                {
                                    for (int e = 0; e < sheet.Masks[idx].Count; e++)
                                    {
                                        Vector2Int pt = sheet.MaskPoints[sheet.Masks[idx][e]];
                                        float      x  = (float)pt.x;
                                        if (x == (sheet.CellWidth / 2) - 1 || x == sheet.CellWidth - 1)
                                        {
                                            x++;
                                        }
                                        x = 0 - ((sheet.CellWidth / 2) - x);

                                        float y = (float)pt.y;
                                        if (y == (sheet.CellHeight / 2) - 1 || y == sheet.CellHeight - 1)
                                        {
                                            y++;
                                        }
                                        y = y + (sheet.CellHeight / 2);

                                        points.Add(new Vector2(x, sheet.CellHeight - y));
                                    }

                                    var spritePhysicsShapeImporter = new SpritePhysicsShapeImporter(importer);
                                    spritePhysicsShapeImporter.SetPhysicsShape(idx, new List <Vector2[]>()
                                    {
                                        points.ToArray()
                                    });
                                }
                            }
                            catch (Exception ex)
                            {
                                Debug.LogError(ex.Message);
                            }
                        }
                    }

                    AssetDatabase.ImportAsset(fileName, ImportAssetOptions.ForceUpdate);

                    // Build Tiles
                    AssetDatabase.StartAssetEditing();

                    // Initialise Array
                    sprites = AssetDatabase.LoadAllAssetsAtPath("Assets/Resources/Maps/" + mapName + "/" + mapName + ".png");
                    List <Tile> tiles = new List <Tile>();
                    for (int i = 0; i < sprites.Length; i++)
                    {
                        tiles.Add(null);
                    }

                    for (int i = 0; i < sprites.Length; i++)
                    {
                        Sprite sprite = sprites[i] as Sprite;

                        if (sprite != null)
                        {
                            try
                            {
                                int        idx  = Convert.ToInt32(sprite.name.Substring(sprite.name.LastIndexOf('_') + 1));
                                ActionTile tile = ScriptableObject.CreateInstance <ActionTile>();
                                tile.colliderType = sheet.Masks[idx].Count == 0 ? Tile.ColliderType.None : Tile.ColliderType.Sprite;
                                tile.hideFlags    = HideFlags.None;
                                tile.sprite       = sprite;
                                tile.name         = sprite.name;

                                path = "Assets/Resources/Maps/" + mapName + "/" + mapName + "_Tile_" + idx.ToString() + ".asset";
                                AssetDatabase.CreateAsset(tile, path);
                            }
                            catch (Exception ex)
                            {
                                Debug.LogError(ex.Message);
                            }
                        }
                    }

                    AssetDatabase.StopAssetEditing();
                }

                // Create Map GameObject
                GameObject go  = new GameObject(mapName);
                MapObject  map = go.AddComponent <MapObject>();

                map.Name            = mapName;
                map.SpriteSheetName = mapInfo.SpriteSheetName;
                map.MapWidth        = mapInfo.MapWidth;
                map.MapHeight       = mapInfo.MapHeight;
                map.TileWidth       = mapInfo.CellWidth;
                map.TileHeight      = mapInfo.CellHeight;

                // Add Points of Interest
                foreach (PointOfInterest poi in mapInfo.POI)
                {
                    map.PointOfInterestNames.Add(poi.Name);
                    map.PointsOfInterest.Add(new POI()
                    {
                        Name = poi.Name, Location = new Vector2Int(poi.x, poi.y)
                    });
                }

                ////public Dictionary<string, NPCController.NPC> NPCs = new Dictionary<string, NPCController.NPC>();
                ////public List<List<bool>> PathFindingGrid = new List<List<bool>>();

                // Store Map Layers and Cells Information
                string json = JsonConvert.SerializeObject(mapInfo.Layers);
                map.LayersJson = json;

                // Store Tile Attributes Information
                if (hasSpriteSheet)
                {
                    json             = JsonConvert.SerializeObject(sheet.MetaData);
                    map.MetaDataJson = json;
                }

                // Store NPC Json
                map.NPCJson = JsonConvert.SerializeObject(mapInfo.NPC);

                // Create Prefab
                string localPath = "Assets/Resources/Maps/" + mapName + ".prefab";
                PrefabUtility.SaveAsPrefabAsset(go, localPath);

                // Delete Update file
                File.Delete(unityFolder + "\\" + mapName + "_update.txt");
            }
        }
    }
    static void ProcessTexture(Texture2D texture)
    {
        string path     = AssetDatabase.GetAssetPath(texture);
        var    importer = AssetImporter.GetAtPath(path) as TextureImporter;

        //importer.isReadable = true;
        importer.textureType        = TextureImporterType.Sprite;
        importer.spriteImportMode   = SpriteImportMode.Multiple;
        importer.mipmapEnabled      = false;
        importer.filterMode         = FilterMode.Point;
        importer.spritePivot        = Vector2.down;
        importer.textureCompression = TextureImporterCompression.Uncompressed;

        var textureSettings = new TextureImporterSettings();         // need this stupid class because spriteExtrude and spriteMeshType aren't exposed on TextureImporter

        importer.ReadTextureSettings(textureSettings);
        textureSettings.spriteMeshType = SpriteMeshType.Tight;
        textureSettings.spriteExtrude  = 0;

        importer.SetTextureSettings(textureSettings);

        int minimumSpriteSize = 128;
        int extrudeSize       = 0;

        Rect[] rects = InternalSpriteUtility.GenerateGridSpriteRectangles(texture, Vector2.zero, new Vector2(minimumSpriteSize, minimumSpriteSize), Vector2.zero);
        Debug.Log(rects.Length);
        var rectsList = new List <Rect>(rects);

        rectsList = SortRects(rectsList, texture.width);

        string filenameNoExtension = Path.GetFileNameWithoutExtension(path);
        var    metas   = importer.spritesheet.ToList();
        int    rectNum = 0;

        foreach (Rect rect in rectsList)
        {
            bool overlaps = false;
            foreach (var other in metas)
            {
                if (other.rect.Overlaps(rect))
                {
                    overlaps = true;
                    break;
                }
            }

            if (overlaps)
            {
                continue;
            }

            var meta = new SpriteMetaData();
            meta.pivot     = Vector2.down;
            meta.alignment = (int)SpriteAlignment.Center;
            meta.rect      = rect;
            meta.name      = filenameNoExtension + "_" + rectNum++;
            metas.Add(meta);
        }

        for (int i = 0; i < metas.Count; i++)
        {
            var m = metas[i];
            m.alignment = (int)SpriteAlignment.Center;
            m.pivot     = new Vector2(0.5f, 0.5f);
            Debug.Log(m);
            metas[i] = m;
        }

        importer.spritesheet = metas.ToArray();

        AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
    }
Exemplo n.º 18
0
    private static void ImportEditorCharacters()
    {
        string path = EditorUtility.OpenFolderPanel("Import Sprite Editor Characters", "", "");

        string[] mapFolders = Directory.GetDirectories(path);
        foreach (string characterFolder in mapFolders)
        {
            string unityFolder   = characterFolder + "\\Unity";
            string characterName = characterFolder.Substring(characterFolder.IndexOf("\\") + 1).Replace(" ", "_");

            if (Directory.Exists(unityFolder))
            {
                Sheet     sheet   = null;
                Texture2D texture = null;

                bool needUpdate = ReadCharacterJsonFile(unityFolder, characterName, ref texture, ref sheet);

                if (needUpdate)
                {
                    // Add the image to the assets library
                    texture.name = characterName;
                    var    bytes     = texture.EncodeToPNG();
                    string assetPath = "Assets/Resources/Characters/" + characterName + "/";

                    if (!Directory.Exists(assetPath))
                    {
                        Directory.CreateDirectory(assetPath);
                    }

                    string fileName = assetPath + characterName + ".png";
                    File.WriteAllBytes(fileName, bytes);
                    AssetDatabase.Refresh();
                    AssetDatabase.ImportAsset(fileName);
                    TextureImporter importer = AssetImporter.GetAtPath(fileName) as TextureImporter;
                    if (importer.spriteImportMode == SpriteImportMode.Multiple)
                    {
                        importer.spriteImportMode = SpriteImportMode.Single;
                        AssetDatabase.WriteImportSettingsIfDirty(fileName);
                    }
                    TextureImporterSettings settings = new TextureImporterSettings();
                    importer.ReadTextureSettings(settings);
                    settings.spriteGenerateFallbackPhysicsShape = false;
                    importer.SetTextureSettings(settings);

                    importer.spriteImportMode    = SpriteImportMode.Multiple;
                    importer.textureType         = TextureImporterType.Sprite;
                    importer.spritePixelsPerUnit = sheet.CellWidth;

                    // Build Sprite Sheet
                    Rect[] rects = InternalSpriteUtility.GenerateGridSpriteRectangles(texture, new Vector2(0, 0), new Vector2(sheet.CellWidth, sheet.CellHeight), new Vector2(0, 0), true);

                    var metas   = new List <SpriteMetaData>();
                    int rectNum = 0;

                    foreach (Rect rect in rects)
                    {
                        var meta = new SpriteMetaData();
                        meta.pivot     = Vector2.zero;
                        meta.alignment = (int)SpriteAlignment.Center;
                        meta.rect      = rect;
                        meta.name      = characterName + "_" + rectNum++;
                        metas.Add(meta);
                    }

                    importer.spritesheet = metas.ToArray();

                    AssetDatabase.ImportAsset(fileName, ImportAssetOptions.ForceUpdate);

                    // Set Physics Shapes
                    UnityEngine.Object[] sprites = AssetDatabase.LoadAllAssetsAtPath("Assets/Resources/Characters/" + characterName + "/" + characterName + ".png");

                    for (int i = 0; i < sprites.Length; i++)
                    {
                        Sprite sprite = sprites[i] as Sprite;

                        if (sprite != null)
                        {
                            try
                            {
                                int            idx    = Convert.ToInt32(sprite.name.Substring(sprite.name.LastIndexOf('_') + 1));
                                List <Vector2> points = new List <Vector2>();
                                if (sheet.Masks[idx].Count > 0)
                                {
                                    for (int e = 0; e < sheet.Masks[idx].Count; e++)
                                    {
                                        Vector2Int pt = sheet.MaskPoints[sheet.Masks[idx][e]];
                                        float      x  = (float)pt.x;
                                        if (x == (sheet.CellWidth / 2) - 1 || x == sheet.CellWidth - 1)
                                        {
                                            x++;
                                        }
                                        x = 0 - ((sheet.CellWidth / 2) - x);

                                        float y = (float)pt.y;
                                        if (y == (sheet.CellHeight / 2) - 1 || y == sheet.CellHeight - 1)
                                        {
                                            y++;
                                        }
                                        y = y + (sheet.CellHeight / 2);

                                        points.Add(new Vector2(x, sheet.CellHeight - y));
                                    }

                                    var spritePhysicsShapeImporter = new SpritePhysicsShapeImporter(importer);
                                    spritePhysicsShapeImporter.SetPhysicsShape(idx, new List <Vector2[]>()
                                    {
                                        points.ToArray()
                                    });
                                }
                            }
                            catch (Exception ex)
                            {
                                Debug.LogError(ex.Message);
                            }
                        }
                    }

                    AssetDatabase.ImportAsset(fileName, ImportAssetOptions.ForceUpdate);

                    // Create Animated Sprite
                    GameObject character = new GameObject("New Sprite");

                    character.layer = LayerMask.NameToLayer("Player & NPC");

                    SpriteRenderer renderer = character.AddComponent <SpriteRenderer>();
                    renderer.sprite   = Resources.Load <Sprite>("Characters/" + characterName + "/" + characterName + "_1");
                    renderer.drawMode = SpriteDrawMode.Simple;
                    renderer.enabled  = true;

                    SpriteAnimator animator = character.AddComponent <SpriteAnimator>();
                    animator.AnimationsJson  = "{'Animations':" + JsonConvert.SerializeObject(sheet.Animations) + "}";
                    animator.SpriteCount     = sprites.Length - 1;
                    animator.SpriteSheetName = characterName;

                    // Create Prefab
                    string localPath = "Assets/Resources/Characters/" + characterName + ".prefab";
                    PrefabUtility.SaveAsPrefabAsset(character, localPath);

                    // Delete Update file
                    File.Delete(unityFolder + "\\" + characterName + "_update.txt");
                }
            }
        }
    }
Exemplo n.º 19
0
        public static void ApplyDefaultTextureSettings(
            SpriteSettings prefs,
            bool changePivot,
            bool changePackingTag)
        {
            if (prefs == null)
            {
                return;
            }

            foreach (var obj in Selection.objects)
            {
                if (!AssetDatabase.Contains(obj))
                {
                    continue;
                }

                string path = AssetDatabase.GetAssetPath(obj);

                var importer = AssetImporter.GetAtPath(path) as TextureImporter;
                if (importer == null)
                {
                    continue;
                }

                // Try to slice it
                var             fileName        = Path.GetFileNameWithoutExtension(path);
                SpriteSheetData spriteSheetData = GetSpriteData(path, prefs.SpritesheetDataFile);

                // When we have text file data
                if (spriteSheetData != null)
                {
                    var gridRects = InternalSpriteUtility.GenerateGridSpriteRectangles(
                        AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D,
                        Vector2.zero, spriteSheetData.Size, Vector2.zero);

                    var spriteSheet = importer.spritesheet ?? new SpriteMetaData[gridRects.Length];

                    if (importer.spritesheet != null)
                    {
                        spriteSheet = spriteSheet.Concat(new SpriteMetaData[Mathf.Max(0, gridRects.Length - importer.spritesheet.Length)]).ToArray();
                    }

                    for (var i = 0; i < spriteSheet.Length; i++)
                    {
                        bool sliceExists = importer.spritesheet != null && i < importer.spritesheet.Length;
                        bool changed     = changePivot || !(sliceExists);
                        spriteSheet[i] = new SpriteMetaData
                        {
                            alignment = changed ? (int)prefs.Pivot : spriteSheet[i].alignment,
                            pivot     = changed ? prefs.CustomPivot : spriteSheet[i].pivot,
                            name      = sliceExists ? spriteSheet[i].name : fileName + "_" + Array.IndexOf(gridRects, gridRects[i]),
                            rect      = gridRects[i]
                        };
                    }

                    // If we don't do this it won't update the new sprite meta data
                    importer.spriteImportMode = SpriteImportMode.Single;
                    importer.spriteImportMode = SpriteImportMode.Multiple;

                    if (spriteSheetData.Frames > 0)
                    {
                        importer.spritesheet = spriteSheet.Take((int)spriteSheetData.Frames).ToArray();
                    }
                    else
                    {
                        importer.spritesheet = spriteSheet;
                    }
                }
                else if (importer.spritesheet != null && changePivot) // for existing sliced sheets without data in the text file and wantint to change pivot
                {
                    var spriteSheet = new SpriteMetaData[importer.spritesheet.Length];

                    for (int i = 0; i < importer.spritesheet.Length; i++)
                    {
                        var spriteMetaData = importer.spritesheet[i];
                        spriteMetaData.alignment = (int)prefs.Pivot;
                        spriteMetaData.pivot     = prefs.CustomPivot;
                        spriteSheet[i]           = spriteMetaData;
                    }

                    importer.spritesheet = spriteSheet;
                }
                else
                {
                    importer.spriteImportMode = SpriteImportMode.Single;
                }

                TextureImporterSettings settings = new TextureImporterSettings();
                importer.ReadTextureSettings(settings);

                settings.filterMode     = prefs.FilterMode;
                settings.wrapMode       = prefs.WrapMode;
                settings.mipmapEnabled  = prefs.GenerateMipMaps;
                settings.textureFormat  = prefs.TextureFormat;
                settings.maxTextureSize = prefs.MaxSize;

                settings.spritePixelsPerUnit = prefs.PixelsPerUnit;

                settings.spriteExtrude  = (uint)Mathf.Clamp(prefs.ExtrudeEdges, 0, 32);
                settings.spriteMeshType = prefs.SpriteMeshType;

                if (changePivot)
                {
                    settings.spriteAlignment = (int)prefs.Pivot;
                    if (prefs.Pivot == SpriteAlignment.Custom)
                    {
                        settings.spritePivot = prefs.CustomPivot;
                    }
                }

                if (changePackingTag)
                {
                    importer.spritePackingTag = prefs.PackingTag;
                }

                importer.SetTextureSettings(settings);
#if UNITY_5_0
                importer.SaveAndReimport();
#else
                AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
#endif
                EditorUtility.SetDirty(obj);
            }
        }
Exemplo n.º 20
0
        void OnGUI()
        {
            EnemyName   = EditorGUILayout.TextField("Enemy Name", EnemyName);
            SpriteSizes = EditorGUILayout.IntField("Sprite Size (32/64)", SpriteSizes);

            ScriptableObject target = this;
            SerializedObject so     = new SerializedObject(target);

            SerializedProperty textureProp = so.FindProperty("ImagePng");

            EditorGUILayout.PropertyField(textureProp, true); // True means show children
            so.ApplyModifiedProperties();                     // Remember to apply modified properties

            so.Update();
            AnimationOrder.DoLayoutList();
            so.ApplyModifiedProperties();             // Remember to apply modified properties

            skipImportStep = EditorGUILayout.Toggle("Skip Import Step?", skipImportStep);


            if (GUILayout.Button("Create Enemy"))
            {
                string path = AssetDatabase.GetAssetPath(ImagePng);

                if (!skipImportStep)
                {
                    TextureImporter importer = (TextureImporter)TextureImporter.GetAtPath(path);
                    importer.wrapMode           = TextureWrapMode.Clamp;
                    importer.textureType        = TextureImporterType.Sprite;
                    importer.spriteImportMode   = SpriteImportMode.Multiple;
                    importer.filterMode         = FilterMode.Point;
                    importer.textureCompression = TextureImporterCompression.Uncompressed;

                    EditorUtility.SetDirty(importer);
                    importer.SaveAndReimport();

                    Rect[] rects = InternalSpriteUtility.GenerateGridSpriteRectangles(ImagePng, Vector2.zero, new Vector2(SpriteSizes, SpriteSizes),
                                                                                      Vector2.zero);

                    string filenameNoExtension  = Path.GetFileNameWithoutExtension(path);
                    List <SpriteMetaData> metas = new List <SpriteMetaData>();
                    int rectNum = 0;

                    foreach (Rect rect in rects)
                    {
                        SpriteMetaData meta = new SpriteMetaData();
                        meta.rect = rect;
                        meta.name = filenameNoExtension + "_" + rectNum++;
                        metas.Add(meta);
                    }

                    importer.spritesheet = metas.ToArray();

                    EditorUtility.SetDirty(importer);
                    importer.SaveAndReimport();
                }

                Sprite[] spriteSheet = AssetDatabase.LoadAllAssetsAtPath(path).OfType <Sprite>().ToArray();
                spriteSheet = spriteSheet.OrderBy(l => l.name, new NaturalComparer()).ToArray();

                List <Anim> anims           = new List <Anim>();
                int         totalFrameCount = 0;

                for (int i = 0; i < AnimationOrder.count; i++)
                {
                    string name           = AnimationOrder.serializedProperty.GetArrayElementAtIndex(i).FindPropertyRelative("name").stringValue;
                    int    frameCount     = AnimationOrder.serializedProperty.GetArrayElementAtIndex(i).FindPropertyRelative("frameCount").intValue;
                    int    millisPerFrame = AnimationOrder.serializedProperty.GetArrayElementAtIndex(i).FindPropertyRelative("milliPerFrame").intValue;

                    totalFrameCount += frameCount;
                    anims.Add(new Anim(name, frameCount, millisPerFrame));
                }

                if (totalFrameCount != spriteSheet.Length)
                {
                    throw new Exception("Total Frames do not equal number of sprites!");
                }

                bool   loadedData    = true;
                string EnemyDataPath = Path.Combine(Path.GetDirectoryName(path), EnemyName + ".asset");

                EnemyData enemyScriptableObject = AssetDatabase.LoadAssetAtPath <EnemyData>(EnemyDataPath);

                if (enemyScriptableObject == null)
                {
                    enemyScriptableObject = CreateInstance <EnemyData>();
                    loadedData            = false;
                }

                enemyScriptableObject.DeadSprite = spriteSheet[spriteSheet.Length - 1];
                enemyScriptableObject.Portrait   = spriteSheet[0];

                totalFrameCount = 0;
                for (int i = 0; i < anims.Count; i++)
                {
                    AnimationClip ac = CreateAnimation(anims[i], spriteSheet.Skip(totalFrameCount).Take(anims[i].frameCount).ToArray(), EnemyName, path);

                    switch (anims[i].name)
                    {
                    case "SideIdle":
                        enemyScriptableObject.SideIdleAnimation = ac;
                        break;

                    case "SideRandom":
                        enemyScriptableObject.RandomAnimation = ac;
                        break;

                    case "Idle":
                        enemyScriptableObject.Idle = ac;
                        break;

                    case "Flinch":
                        enemyScriptableObject.Flinch = ac;
                        break;

                    case "BeforeAttack":
                        enemyScriptableObject.BeforeAttack = ac;
                        break;

                    case "AttackExecute":
                        enemyScriptableObject.AttackExecute = ac;
                        break;

                    case "AfterAttack":
                        if (anims[i].frameCount != 0)
                        {
                            enemyScriptableObject.AfterAttack = ac;
                        }
                        else
                        {
                            enemyScriptableObject.AfterAttack = CreateAnimation(new Anim("AfterAttack", 1, 1000), new[] { spriteSheet[totalFrameCount + anims[i].frameCount - 1] }, EnemyName, path);
                        }
                        break;

                    case "Death":
                        enemyScriptableObject.Death = ac;
                        // If this is the death animation then create a dead animation that is just the last frame of the death animation
                        Sprite deadSprite = spriteSheet[totalFrameCount + anims[i].frameCount - 1];
                        enemyScriptableObject.Dead       = CreateAnimation(new Anim("Dead", 1, 1000), new[] { deadSprite }, EnemyName, path);
                        enemyScriptableObject.DeadSprite = deadSprite;
                        break;

                    case "Walking":
                        enemyScriptableObject.Walking = ac;
                        break;
                    }

                    totalFrameCount += anims[i].frameCount;
                }

                if (!loadedData)
                {
                    AssetDatabase.CreateAsset(enemyScriptableObject, EnemyDataPath);
                }
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();
            }
        }
        private void ImportSpriteSheetIntoAnimation(Texture2D spriteSheet, int animIdx = -1)
        {
            string assetPath = AssetDatabase.GetAssetPath(spriteSheet);

            if (string.IsNullOrEmpty(assetPath))
            {
                return;
            }
            TextureImporter spriteSheetImporter = (TextureImporter)TextureImporter.GetAtPath(assetPath);

            int characterNb;
            int charRowLength;
            int charColumnLength;
            int charFramesCount = m_target.DirectionsPerAnim * m_target.FramesPerAnim;
            int columns = 0, rows = 0;

            if (spriteSheetImporter.textureType != TextureImporterType.Sprite ||
                spriteSheetImporter.spriteImportMode != SpriteImportMode.Multiple ||
                spriteSheetImporter.spritesheet.Length == 0 ||
                spriteSheetImporter.spritesheet.Length % charFramesCount != 0)
            {
                Rect[] rects = InternalSpriteUtility.GenerateAutomaticSpriteRectangles(spriteSheet, 4, 0);
                if (rects.Length > 0 && rects.Length % charFramesCount == 0)
                {
                    for (; columns < rects.Length; ++columns)
                    {
                        //NOTE: the order of slicing in GenerateAutomaticSpriteRectangles is from bottom to top, not from top to bottom like Sprite Editor Slicing
                        if (rects[columns].yMin >= rects[0].yMax)
                        {
                            rows = rects.Length / columns;
                            break;
                        }
                    }
                }
                else
                {
                    columns = m_target.FramesPerAnim;
                    rows    = m_target.DirectionsPerAnim;
                }

                charRowLength    = Mathf.Max(1, columns / m_target.FramesPerAnim);
                charColumnLength = Mathf.Max(1, rows / m_target.FramesPerAnim);
                characterNb      = charRowLength * charColumnLength;

                int spriteCount = charFramesCount * characterNb;
                SpriteMetaData[] aSpriteMetaData = spriteSheetImporter.spritesheet;
                if (spriteSheetImporter.spritesheet.Length != spriteCount || spriteSheetImporter.spriteImportMode != SpriteImportMode.Multiple)
                {
                    aSpriteMetaData = new SpriteMetaData[spriteCount];
                    spriteSheetImporter.textureType      = TextureImporterType.Sprite;
                    spriteSheetImporter.spriteImportMode = SpriteImportMode.Multiple;
                    spriteSheetImporter.filterMode       = FilterMode.Point;
                    spriteSheetImporter.mipmapEnabled    = false;
                    spriteSheetImporter.textureFormat    = TextureImporterFormat.AutomaticTruecolor;
                    Rect spriteRect = new Rect(0, 0, spriteSheet.width / (m_target.FramesPerAnim * charRowLength), spriteSheet.height / (m_target.DirectionsPerAnim * charColumnLength));
                    for (int gy = 0, spriteIdx = 0; gy < rows; ++gy)
                    {
                        for (int gx = 0; gx < columns; ++gx, ++spriteIdx)
                        {
                            spriteRect.position = new Vector2(gx * spriteRect.width, spriteSheet.height - (1 + gy) * spriteRect.height);
                            SpriteMetaData spriteMetaData = new SpriteMetaData();
                            //int characterIdx = (gy / m_target.DirectionNb) * charRowLength + (gx / m_target.FramesPerAnim);

                            //NOTE: the sprites are sorted alphabetically, so spriteIdx should be in the first place after the name and nothing else
                            spriteMetaData.name        = spriteSheet.name + "_" + spriteIdx; // + (characterNb > 1 ? ("_" + characterIdx) : "") + "_" + gy + "_" + gx;
                            spriteMetaData.rect        = spriteRect;
                            aSpriteMetaData[spriteIdx] = spriteMetaData;
                        }
                    }
                    spriteSheetImporter.spritesheet = aSpriteMetaData;
                    AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
                }
            }

            UpdateAligmentAndPivot(spriteSheet);

            List <Sprite> sprites = new List <Sprite>(AssetDatabase.LoadAllAssetsAtPath(assetPath).OfType <Sprite>().ToArray());

            //sort them properly using the last number
            sprites = sprites.OrderBy(s => int.Parse(s.name.Substring(s.name.LastIndexOf("_") + 1))).ToList();
            for (; columns < sprites.Count; ++columns)
            {
                if (sprites[columns].rect.yMax <= sprites[0].rect.yMin)
                {
                    rows = sprites.Count / columns;
                    break;
                }
            }

            if (columns * rows != sprites.Count || columns % m_target.FramesPerAnim != 0 || rows % m_target.DirectionsPerAnim != 0)
            {
                Debug.LogError("Something was wrong with the sprite sheet. Try slicing it again using the Sprite Editor using grid settings or set the Sprite Mode to single and try again.");
                return;
            }

            List <Sprite> sortedSprites = new List <Sprite>();

            charRowLength    = Mathf.Max(1, columns / m_target.FramesPerAnim);
            charColumnLength = Mathf.Max(1, rows / m_target.FramesPerAnim);
            for (int charY = 0; charY < charColumnLength; ++charY)
            {
                for (int charX = 0; charX < charRowLength; ++charX)
                {
                    for (int c = 0; c < m_target.DirectionsPerAnim; ++c)
                    {
                        for (int r = 0; r < m_target.FramesPerAnim; ++r)
                        {
                            int gx = charX * m_target.FramesPerAnim + r;
                            int gy = charY * m_target.DirectionsPerAnim + c;
                            sortedSprites.Add(sprites[gy * columns + gx]);
                        }
                    }
                }
            }
            characterNb = sortedSprites.Count / charFramesCount;

            if (animIdx >= 0)
            {
                ImportSpriteSheetIntoAnimation(spriteSheet, sortedSprites.Take(charFramesCount).ToArray(), animIdx, spriteSheet.name);
            }
            else
            {
                for (int characterIdx = 0; characterIdx < characterNb; ++characterIdx)
                {
                    Sprite[] characterSprites = sortedSprites.Skip(characterIdx * charFramesCount).Take(charFramesCount).ToArray();
                    string   charName         = spriteSheet.name + (characterNb > 1? ("_" + characterIdx) : "");
                    ImportSpriteSheetIntoAnimation(spriteSheet, characterSprites, m_target.GetAnimList().FindIndex(x => x.name == charName), charName);
                }
            }
        }
Exemplo n.º 22
0
    static void ProcessSubtileTexture(Texture2D _texture, AutoTileLookup _lookup)
    {
        //Spprite importer stuff to prep the asset for slicing.
        string path     = AssetDatabase.GetAssetPath(_texture);
        var    importer = AssetImporter.GetAtPath(path) as TextureImporter;


        importer.textureType        = TextureImporterType.Sprite;
        importer.spriteImportMode   = SpriteImportMode.Multiple;
        importer.mipmapEnabled      = false;
        importer.filterMode         = FilterMode.Point;
        importer.spritePivot        = Vector2.down;
        importer.textureCompression = TextureImporterCompression.Uncompressed;

        var textureSettings = new TextureImporterSettings();

        importer.ReadTextureSettings(textureSettings);
        textureSettings.spriteMeshType = SpriteMeshType.FullRect;
        textureSettings.spriteExtrude  = 0;

        importer.SetTextureSettings(textureSettings);

        //for A2s we know the subtil size is width/4
        int minSpriteSize = _texture.width / 4;

        //Slice the asset
        Rect[] rects = InternalSpriteUtility.GenerateGridSpriteRectangles(
            _texture,
            Vector2.zero,
            new Vector2(minSpriteSize, minSpriteSize),
            Vector2.zero);

        List <Rect> rectList = new List <Rect>(rects);

        string filenameNoExtension  = Path.GetFileNameWithoutExtension(path);
        List <SpriteMetaData> metas = new List <SpriteMetaData>();
        int count = 0;

        foreach (Rect rect in rectList)
        {
            var meta = new SpriteMetaData();
            meta.pivot     = Vector2.one * 0.5f;//center
            meta.alignment = (int)SpriteAlignment.Center;
            meta.rect      = rect;
            int xpos = count % 4;
            int ypos = Mathf.CeilToInt(count / 4);

            int rightside = xpos % 2;
            int topside   = (ypos + 1) % 2;
            int lookup    = (topside * 2) + rightside;


            meta.name = RuleTileEditor.m_ModDirections[lookup] + count.ToString("00") + "_" + filenameNoExtension;
            metas.Add(meta);
            count++;
        }

        importer.spritesheet = metas.ToArray();

        AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
        Object[]      objects = AssetDatabase.LoadAllAssetsAtPath(path);
        List <Sprite> sprites = new List <Sprite>();

        for (int i = 0; i < objects.Length; i++)
        {
            //filter out non-sprites.  I was getting some extra entry here.
            if ((objects[i] as Sprite) != null)
            {
                sprites.Add(objects[i] as Sprite);
            }
        }
        sprites.Sort((Sprite x, Sprite y) => x.name.CompareTo(y.name));

        RuleTile m_tile = ScriptableObject.CreateInstance <RuleTile>();

        m_tile.m_TilingRules = new List <RuleTile.TilingRule>();

        int rulecount = 0;

        for (int i = 255; i >= 0; i--)
        {
            RuleTile.TilingRule rule = ImportAutotile.GetRule(i);
            if (rule != null)
            {
                AddSpritesToRule(ref rule, sprites, rulecount, _lookup);

                rulecount++;
                m_tile.m_TilingRules.Add(rule);
            }
        }

        AssetDatabase.CreateAsset(m_tile, "Assets/" + filenameNoExtension + "tile.asset");
    }