Example #1
0
 static void clearAllTextures()
 {
     foreach (var sheet in SKTextureUtil.getAllSpriteSheets())
     {
         sheet.material.mainTexture = null;
     }
 }
    private bool isAnimationNameValid()
    {
        if (_allSpriteAnimations == null)
        {
            _allSpriteAnimations = SKTextureUtil.getAllSpriteAnimations();
        }

        // validate that there are images in the folder and that the name has not been used
        foreach (var s in _allSpriteAnimations)
        {
            if (s.name == animationName)
            {
                return(false);
            }
        }

        return(true);
    }
    void OnGUI()
    {
        _generateSDTexture  = EditorGUILayout.Toggle("Auto-generate SD texture", _generateSDTexture);
        _orthoSize          = EditorGUILayout.IntField("Camera Ortho Size", _orthoSize);
        _targetScreenHeight = EditorGUILayout.IntField("Target Screen Height", _targetScreenHeight);

        GUI.enabled = false;
        EditorGUILayout.TextField("Image source folder", _sourceFolder);
        GUI.enabled = true;

        EditorGUILayout.HelpBox("If your camera is setup with matching settings to your sprite sheet all sprites will automatically be pixel perfect.", MessageType.None);


        GUILayout.Space(25);

        if (GUILayout.Button("Choose Image Source Folder"))
        {
            var folder = EditorUtility.OpenFolderPanel("SpriteKit Image Source Folder", "Assets", null);
            if (folder != string.Empty)
            {
                if (!folder.Contains("Assets"))
                {
                    EditorUtility.DisplayDialog("SpriteKit Error", "The folder you chose is outside of your project folder. The folder must already be in your project.", "OK");
                }
                else
                {
                    _sourceFolder = SKTextureUtil.makePathRelativeToProject(folder);
                }
            }
        }

        GUILayout.Space(15);

        if (GUILayout.Button("Create Sprite Sheet"))
        {
            if (_sourceFolder == null || _sourceFolder == string.Empty)
            {
                return;
            }

            SKTextureUtil.createSpriteSheet(Path.GetFileName(_sourceFolder), _sourceFolder, _generateSDTexture, _orthoSize, _targetScreenHeight);
            Close();
        }
    }
Example #4
0
    public override void OnInspectorGUI()
    {
        //base.OnInspectorGUI();
        _sprite = (SKSprite)target;

        // sprite properties
        if (_sprite.spriteSheet != null)
        {
            _sprite.desiredSize = EditorGUILayout.Vector2Field("Desired Size", _sprite.desiredSize);

            if (GUILayout.Button("Set Size to Image Size"))
            {
                Undo.RegisterUndo(_sprite, "Undo Make Pixel Perfect");
                _sprite.desiredSize = _sprite.pixelPerfectHDSize;
                GUI.changed         = true;
            }
        }
        _sprite.tintColor = EditorGUILayout.ColorField("Tint Color", _sprite.tintColor);
        _sprite.anchor    = anchorSelector(_sprite.anchor, "Sprite Anchor");


        // sprite sheet
        var spriteSheets            = SKTextureUtil.getAllSpriteSheets().Select(x => x.name).ToList();
        var spriteSheetSeletedIndex = 0;

        if (_sprite.spriteSheet == null)
        {
            spriteSheets.Insert(0, "Choose Sprite Sheet");
        }
        else
        {
            // we have a sprite sheet. we want it to be selected
            spriteSheetSeletedIndex = Array.IndexOf(spriteSheets.ToArray(), _sprite.spriteSheet.name);
        }

        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("Sprite Sheet");
        var newSpriteSheetIndex = EditorGUILayout.Popup(spriteSheetSeletedIndex, spriteSheets.ToArray());

        EditorGUILayout.EndHorizontal();

        if (newSpriteSheetIndex != spriteSheetSeletedIndex)
        {
            _sprite.spriteSheet       = SKTextureUtil.getAllSpriteSheets().Where(x => x.name == spriteSheets[newSpriteSheetIndex]).Select(x => x).First();
            _sprite.renderer.material = _sprite.spriteSheet.material;
            _sprite.sourceImageName   = _sprite.spriteSheet.containedImages[0];
        }



        if (_sprite.spriteSheet != null)
        {
            var currentIndex = -1;

            var currentImage = _sprite.spriteSheet.containedImages.Where(item => _sprite.sourceImageName != null && item.EndsWith(_sprite.sourceImageName)).FirstOrDefault();
            if (currentImage != null)
            {
                currentIndex = Array.IndexOf(_sprite.spriteSheet.containedImages, currentImage);
            }

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Sprite Name");
            var newIndex = EditorGUILayout.Popup(currentIndex, _sprite.spriteSheet.containedImages);
            EditorGUILayout.EndHorizontal();

            if (currentIndex != newIndex)
            {
                var selectedImage = _sprite.spriteSheet.containedImages[newIndex];
                var textureInfo   = _sprite.spriteSheet.textureInfoForSourceImage(selectedImage);

                _sprite.pixelPerfectHDSize = textureInfo.size;
                _sprite.desiredSize        = textureInfo.size;
                _sprite.sourceImageName    = selectedImage;
                _sprite.Awake();
            }
        }


        GUILayout.Space(10);

        if (_sprite.spriteSheet != null)
        {
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Refresh Sprite Sheet"))
            {
                _sprite.spriteSheet.refreshSourceImages();
                refreshAllSprites();
            }


            // save colors so we can reset after making the destructive button
            var previousContentColor = GUI.contentColor;
            var previousBGColor      = GUI.backgroundColor;
            GUI.contentColor    = Color.red;
            GUI.backgroundColor = Color.red;

            if (GUILayout.Button("Delete Sprite Sheet"))
            {
                if (EditorUtility.DisplayDialog("SpriteKit Destruction Action Warning", "Are you sure you want to delete this sprite sheet?", "Yes, I'm Sure", "No!"))
                {
                    // kill all assets associated with this sprite sheet
                    var material = _sprite.spriteSheet.getMaterial(false);
                    AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(material.mainTexture));

                    if (_sprite.spriteSheet.hasHdAtlas)
                    {
                        material = _sprite.spriteSheet.getMaterial(true);
                        AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(material.mainTexture));
                    }

                    // all done with the textures so now we kill the material
                    AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(material));

                    // find any animations that reference this sprite sheet
                    var allSpriteAnimations = SKTextureUtil.getAllSpriteAnimations().Where(anim => anim.spriteSheet == _sprite.spriteSheet).ToArray();
                    foreach (var animation in allSpriteAnimations)
                    {
                        AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(animation));
                    }

                    AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(_sprite.spriteSheet));
                    _sprite.spriteSheet     = null;
                    _sprite.sourceImageName = null;
                }
            }
            GUILayout.EndHorizontal();
            GUI.contentColor    = previousContentColor;
            GUI.backgroundColor = previousBGColor;
        }


        if (GUI.changed)
        {
            EditorUtility.SetDirty(target);
            _sprite.Awake();
        }
    }
Example #5
0
    static void createAnimation()
    {
        var textures = new List <Texture2D>();

        // first validate that we have only Texture2Ds
        foreach (var o in Selection.objects)
        {
            if (o is Texture2D)
            {
                textures.Add(o as Texture2D);
            }
        }

        if (textures.Count == 0)
        {
            EditorUtility.DisplayDialog("Cannot Create Sprite Animation", "You did not select any images fool", "OK. I'm sorry.");
            return;
        }

        // figure out what sprite sheet the images are associated with and bail if it is more than one
        var allSpriteSheets = SKTextureUtil.getAllSpriteSheets();
        Func <string, string, SKSpriteSheet> spriteSheetWithImage = (imageName, texturePath) =>
        {
            foreach (var sheet in allSpriteSheets)
            {
                if (texturePath == sheet.imageSourceFolder && sheet.containedImages.Contains(imageName))
                {
                    return(sheet);
                }
            }
            return(null);
        };

        SKSpriteSheet spriteSheetForAnimation = null;
        var           spriteWidth             = textures[0].width;
        var           spriteHeight            = textures[0].height;

        foreach (var tex in textures)
        {
            var texturePath = AssetDatabase.GetAssetPath(tex);
            var theSheet    = spriteSheetWithImage(Path.GetFileName(texturePath), Path.GetDirectoryName(texturePath));

            if (theSheet == null)
            {
                EditorUtility.DisplayDialog("Cannot Create Sprite Animation", "An image was selected that is not in a SKSpriteSheet", "Close");
                return;
            }

            if (spriteSheetForAnimation == null)
            {
                spriteSheetForAnimation = theSheet;
            }
            else
            {
                // if we found a different sprite sheet we stop
                if (spriteSheetForAnimation != theSheet)
                {
                    EditorUtility.DisplayDialog("Cannot Create Sprite Animation", "Images from multiple SKSpriteSheets were chosen", "Close");
                    return;
                }
            }

            if (tex.height != spriteHeight || tex.width != spriteWidth)
            {
                EditorUtility.DisplayDialog("Cannot Create Sprite Animation", "Images of different sizes were found. All images must be the same size for an animation.", "Close");
                return;
            }
        }

        var wizard = SKSpriteAnimationWizard.createWizard();

        wizard.spriteSheet     = spriteSheetForAnimation;
        wizard.animationFrames = textures.Select(t => Path.GetFileName(AssetDatabase.GetAssetPath(t))).OrderBy(t => t, new NaturalSortComparer <string>()).ToArray();
    }
Example #6
0
    public static void refreshSourceImages(this SKSpriteSheet sheet)
    {
        // set a flag while we import the PSD to avoid our AssetPostprocessor from getting an endless loop of death
        isCurrentlyRefreshingSourceImages = true;

        try
        {
            var textureInfoList      = new List <SKTextureInfo>();
            var files                = Directory.GetFiles(sheet.imageSourceFolder).Where(f => !f.EndsWith(".meta")).ToArray();
            var textures             = new Dictionary <string, Texture2D>(files.Length);
            var texturesNotToDestroy = new List <string>();
            var containedImages      = new List <string>();

            float progress = 1f;

            foreach (var f in files)
            {
                EditorUtility.DisplayProgressBar("Creating Sprite Atlases..", "processing image at path: " + f, progress++ / files.Length);

                var       path = Path.Combine(sheet.imageSourceFolder, Path.GetFileName(f));
                Texture2D tex  = null;

                if (Path.GetExtension(path) == ".png")
                {
                    // we load directly from disk so that the textures are guaranteed readable
                    tex = new Texture2D(0, 0);
                    tex.LoadImage(File.ReadAllBytes(f));
                }
                else if (Path.GetExtension(path).ToLower() == ".psd" || Path.GetExtension(path) == ".gif")
                {
                    var texImporter = TextureImporter.GetAtPath(path) as TextureImporter;
                    texImporter.isReadable = true;
                    AssetDatabase.ImportAsset(path);

                    tex = AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D;
                    if (tex != null)
                    {
                        texturesNotToDestroy.Add(tex.name);
                    }
                }


                if (tex != null)
                {
                    textures.Add(Path.GetFileName(f), tex);
                    containedImages.Add(Path.GetFileName(f));
                }
            }

            sheet.containedImages = containedImages.ToArray();

            // pack all the textures and make a lookup dictionary
            var textureArray = textures.Select(x => x.Value).ToArray();
            var rects        = SKTextureUtil.rebuildAtlas(textureArray, sheet.name.Replace("_sheet", string.Empty) + "_atlas", sheet.hasHdAtlas);
            var texToRect    = new Dictionary <string, Rect>(textures.Count);

            for (var i = 0; i < textureArray.Length; i++)
            {
                var key = textures.Where(y => y.Value == textureArray[i]).Select(x => x.Key).First();
                texToRect[key] = rects[i];
            }

            // create our textureInfos
            foreach (var item in texToRect)
            {
                var tex = textures[item.Key];

                var info = new SKTextureInfo();
                info.file   = item.Key;
                info.uvRect = item.Value;
                info.size   = new Vector2(tex.width, tex.height);
                textureInfoList.Add(info);
            }

            // clean up textures
            foreach (var tex in textures)
            {
                // only destroy textures that we loaded from pngs
                if (!texturesNotToDestroy.Contains(tex.Value.name))
                {
                    GameObject.DestroyImmediate(tex.Value, true);
                }
            }
            textures.Clear();

            // not sure why getting the asset path triggers a save but it does for some reason
            AssetDatabase.GetAssetPath(sheet);
            sheet.imageTextureInfo = textureInfoList.ToArray();
            //AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            EditorUtility.SetDirty(sheet);
        }
        catch (System.Exception e)
        {
            Debug.LogError("Something went wrong creating the atlas: " + e);
        }
        finally
        {
            EditorUtility.ClearProgressBar();
            isCurrentlyRefreshingSourceImages = false;
        }
    }