Ejemplo n.º 1
0
    //private static string _atlasPath = "Assets/Atlas/Atlas.spriteatlas";
    //private static string _texturePath = "Assets/Texture";

    //[MenuItem("Tools/AutoSetAtlas")]
    static void AutoSetAtlasContents(string _atlasPath, string _texturePath)
    {
        SpriteAtlas atlas = new SpriteAtlas();
        // 设置参数 可根据项目具体情况进行设置
        SpriteAtlasPackingSettings packSetting = new SpriteAtlasPackingSettings()
        {
            blockOffset        = 1,
            enableRotation     = false,
            enableTightPacking = false,
            padding            = 2,
        };

        atlas.SetPackingSettings(packSetting);

        SpriteAtlasTextureSettings textureSetting = new SpriteAtlasTextureSettings()
        {
            readable        = false,
            generateMipMaps = false,
            sRGB            = true,
            filterMode      = FilterMode.Bilinear,
        };

        atlas.SetTextureSettings(textureSetting);

        TextureImporterPlatformSettings platformSetting = new TextureImporterPlatformSettings()
        {
            maxTextureSize      = 2048,
            format              = TextureImporterFormat.Automatic,
            crunchedCompression = true,
            textureCompression  = TextureImporterCompression.Compressed,
            compressionQuality  = 50,
        };

        atlas.SetPlatformSettings(platformSetting);

        AssetDatabase.CreateAsset(atlas, _atlasPath);

        // 1、添加文件
        DirectoryInfo dir = new DirectoryInfo(_texturePath);

        // 这里我使用的是png图片,已经生成Sprite精灵了
        FileInfo[] files = dir.GetFiles("*.png");
        foreach (FileInfo file in files)
        {
            atlas.Add(new[] { AssetDatabase.LoadAssetAtPath <Sprite>($"{_texturePath}/{file.Name}") });
        }

        // 2、添加文件夹
        Object obj = AssetDatabase.LoadAssetAtPath(_texturePath, typeof(Object));

        atlas.Add(new[] { obj });

        AssetDatabase.SaveAssets();
    }
Ejemplo n.º 2
0
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            SpriteBatch = new SpriteBatch(GraphicsDevice);

            // Load some default fonts.
            MediumFont      = ContentManager.Load <GameFont>("Fonts/MediumFont");
            MediumFont.Size = 24;

            // Load loading icon atlas.
            LoadingIconSprite       = new AnimatedSprite(ContentManager.Load <Texture2D>("Textures/LoadingIconAtlas"), 128, 128, 60);
            LoadingIconSprite.Pivot = new Vector2(0.5f, 0.5f);

            // Create the main sprite atlas.
            SpriteAtlas = new SpriteAtlas(2048, 2048);

            // Loading missing texture sprite.
            MissingTextureSprite       = SpriteAtlas.Add("Textures/MissingTexture");
            MissingTextureSprite.Pivot = new Vector2(0.5f, 1f); // Bottom center.

            // Temporarily load tiles here.
            TreeTile              = SpriteAtlas.Add("Textures/TileComps/Trees");
            MountainTile          = SpriteAtlas.Add("Textures/TileComps/Mountain");
            TileShadowTopRight    = SpriteAtlas.Add("Textures/TileShadowTopRight");
            TileShadowTopLeft     = SpriteAtlas.Add("Textures/TileShadowTopLeft");
            TileShadowBottomRight = SpriteAtlas.Add("Textures/TileShadowBottomRight");
            TileShadowBottomLeft  = SpriteAtlas.Add("Textures/TileShadowBottomLeft");
            HouseTile             = SpriteAtlas.Add("Textures/TileComps/House");

            // Load definitions.
            string defPath = Path.Combine(ContentDirectory, "Defs");

            DefDatabase = new DefDatabase();
            Debug.StartTimer("Load def files");
            DefDatabase.AddAllFromDirectory(defPath);
            Debug.StopTimer(true);
            Debug.StartTimer("Parse & resolve defs");
            DefDatabase.Load();
            Debug.StopTimer(true);

            // Tile loading from defs.
            Debug.StartTimer("Tile def load");
            DefFactory <Tile, TileDef> .Init("Tile");

            Debug.StopTimer(true);

            Debug.StartTimer("Tile comp def load");
            DefFactory <TileComponent, TileCompDef> .Init("TileComp");

            Debug.StopTimer(true);

            Debug.StartTimer("Entity comp def load");
            DefFactory <Entity, EntityDef> .Init("Entity");

            Debug.StopTimer(true);

            SpriteAtlas.Pack(false);

            Loop.Start();
        }
Ejemplo n.º 3
0
        static void GeneratePerAtlas(DirectoryInfo dirInfo)
        {
            var DirName = TarPath + dirInfo.Name;

            if (!Directory.Exists(DirName))
            {
                Directory.CreateDirectory(DirName);
            }
            var AtlasName = DirName + "/" + dirInfo.Name + ".spriteatlas";

            if (File.Exists(AtlasName))
            {
                Directory.Delete(AtlasName, true);
            }

            SpriteAtlas atlas = new SpriteAtlas();

            AssetDatabase.CreateAsset(atlas, AtlasName);
            AtlasSetting(atlas);

            var allFiles = dirInfo.GetFiles("*.png", SearchOption.AllDirectories);

            foreach (FileInfo pngFile in allFiles)
            {
                string str = pngFile.FullName.Substring(pngFile.FullName.IndexOf("Assets"));
                atlas.Add(new[] { AssetDatabase.LoadAssetAtPath <Sprite>(str) });
            }
            //添加文件夹
            //Object obj = AssetDatabase.LoadAssetAtPath(OprPath + dirInfo.Name, typeof(Object));
            //atlas.Add(new[] { obj });

            AssetDatabase.SaveAssets();
        }
Ejemplo n.º 4
0
    /// <summary>
    /// 单个文件夹精灵打包图集。图集逻辑名称为文件夹名
    /// </summary>
    /// <param name="folderPath">精灵文件夹</param>
    /// <param name="dstFolder">图集存放文件夹</param>
    private void SpritePackOneFolder(string folderPath, string dstFolder)
    {
        if (string.IsNullOrEmpty(folderPath) || !Directory.Exists(folderPath))
        {
            Debug.LogError("精灵文件夹路径错误,请选择需要打包的文件夹!");
            return;
        }

        if (string.IsNullOrEmpty(dstFolder) || !Directory.Exists(dstFolder))
        {
            Debug.LogError("精灵文件夹存放路径错误");
            return;
        }

        SpriteAtlas   sa         = new SpriteAtlas();
        var           assetPaths = Directory.GetFiles(folderPath);
        List <Sprite> sprites    = new List <Sprite>();

        foreach (var path in assetPaths)
        {
            if (path.EndsWith(".png")) // && path.Contains("SA_"))
            {
                var replacePath = path.Replace(@"\", "/");
                var obj         = AssetDatabase.LoadAssetAtPath(replacePath, typeof(Sprite)) as Sprite;
                sprites.Add(obj);
            }
        }

        sa.Add(sprites.ToArray());
        var saName = new DirectoryInfo(folderPath).Name;

        AssetDatabase.CreateAsset(sa, dstFolder + "/SA_" + saName + ".spriteatlas");
        Selection.activeObject = sa;
    }
        public void WhenSpriteWithAtlas_SpriteImportDataCreated(SpritePackerMode spriteMode, string spritePackingTag, bool hasReferencingSpriteAtlas, bool expectedPacked)
        {
            string sourceTexture = Path.Combine(kSourceTestAssetFolder, "SpriteTexture32x32.png");
            string destTexture   = Path.Combine(kTestAssetFolder, "SpriteTexture32x32.png");

            AssetDatabase.CopyAsset(sourceTexture, destTexture);
            TextureImporter importer = AssetImporter.GetAtPath(destTexture) as TextureImporter;

            importer.spritePackingTag = spritePackingTag;
            importer.SaveAndReimport();

            if (hasReferencingSpriteAtlas)
            {
                var sa            = new SpriteAtlas();
                var targetObjects = new UnityEngine.Object[] { AssetDatabase.LoadAssetAtPath <Texture>(destTexture) };
                sa.Add(targetObjects);
                string saPath = Path.Combine(kTestAssetFolder, "sa.spriteAtlas");
                AssetDatabase.CreateAsset(sa, saPath);
                AssetDatabase.Refresh();
            }

            GUID.TryParse(AssetDatabase.AssetPathToGUID(destTexture), out GUID spriteGUID);

            CalculateAssetDependencyData.TaskInput input = CreateDefaultInput();
            EditorSettings.spritePackerMode = spriteMode;
            SpriteAtlasUtility.PackAllAtlases(input.Target);
            input.Assets = new List <GUID>()
            {
                spriteGUID
            };
            CalculateAssetDependencyData.RunInternal(input, out CalculateAssetDependencyData.TaskOutput output);

            Assert.AreEqual(expectedPacked, output.AssetResults[0].spriteData.PackedSprite);
        }
Ejemplo n.º 6
0
        public static void NewSpriteAtlas()
        {
            string[] guids = Selection.assetGUIDs;
            sCurSelectObjs.Clear();
            foreach (var id in guids)
            {
                string path = AssetDatabase.GUIDToAssetPath(id);
                Object obj  = AssetDatabase.LoadAssetAtPath(path, typeof(Object));
                LogFile.Warn("path:" + path);
                //LogFile.Log("{0} is native Asset: {1}, is valid folder:{2}", path, AssetDatabase.IsNativeAsset(obj), AssetDatabase.IsValidFolder(path));
                if (AssetDatabase.IsValidFolder(path) || obj as Sprite)
                {
                    sCurSelectObjs.Add(obj);
                }
            }
            string p = EditorUtility.SaveFilePanel("新建 SpriteAtlas", "Assets/" + GameConfig.STR_RES_FOLDER, "NewSpriteAtlas", ".spriteatlas");

            if (string.IsNullOrEmpty(p))
            {
                return;
            }
            p = Tools.RelativeTo(p, Application.dataPath, true);

            SpriteAtlas atlas = new SpriteAtlas();

            atlas.Add(sCurSelectObjs);
            AssetDatabase.CreateAsset(atlas, p);

            AssetDatabase.SaveAssets();
            _clearStatus();
        }
Ejemplo n.º 7
0
    public static void PackAtlas()
    {
        List <string> allAtlasList = new List <string>();
        Dictionary <string, List <string> > spriteAtlasDict = new Dictionary <string, List <string> >();

        string path = "Assets/SpriteAtlas/Atlas";

        string[] allAtlasPaths = Helper.GetFiles(path, null, true, false);

        for (int i = 0; i < allAtlasPaths.Length; i++)
        {
            allAtlasPaths[i] = allAtlasPaths[i].Replace("\\", "/");
            if (!allAtlasPaths[i].Contains(".meta"))
            {
                allAtlasList.Add(allAtlasPaths[i]);
            }
        }

        for (int i = 0; i < allAtlasList.Count; i++)
        {
            string[] split     = allAtlasList[i].Split('/');
            string   atlasName = split[split.Length - 2];
            string   picPath   = split[split.Length - 1];

            if (!spriteAtlasDict.ContainsKey(atlasName))
            {
                List <string> list = new List <string>();
                spriteAtlasDict.Add(atlasName, list);
            }

            spriteAtlasDict[atlasName].Add(picPath);
        }

        string loadPicPath = "Assets/SpriteAtlas/Atlas/";
        string savePath    = "Assets/SpriteAtlas/SpriteAtlas/";

        string[] deletePaths = Helper.GetFiles(savePath);

        for (int i = 0; i < deletePaths.Length; i++)
        {
            File.Delete(deletePaths[i]);
        }

        Helper.CheckPathExistence(savePath);
        foreach (KeyValuePair <string, List <string> > kv in spriteAtlasDict)
        {
            SpriteAtlas sa = new SpriteAtlas();
            AssetDatabase.CreateAsset(sa, savePath + kv.Key.ToString() + ".spriteAtlas");
            List <UnityEngine.Object> objectList = new List <UnityEngine.Object>();
            for (int i = 0; i < kv.Value.Count; i++)
            {
                UnityEngine.Object obj = AssetDatabase.LoadMainAssetAtPath(loadPicPath + kv.Key + "/" + kv.Value[i]);
                objectList.Add(obj);
            }

            sa.Add(objectList.ToArray());
            sa.SetIncludeInBuild(false);
        }
    }
Ejemplo n.º 8
0
    static void ResetAtlas(SpriteAtlas atlas, Object[] objects)
    {
        var oldSprites = atlas.GetPackables();

        atlas.Remove(oldSprites);

        atlas.Add(objects);
    }
    static void CreateFolderEntryAssets(string RootFolder, AddressableAssetSettings settings, AddressableAssetGroup group)
    {
        AssetDatabase.CreateFolder(RootFolder, "folderEntry");
        string folderPath = RootFolder + "/folderEntry";

        {
            var texture = new Texture2D(32, 32);
            var data    = ImageConversion.EncodeToPNG(texture);
            UnityEngine.Object.DestroyImmediate(texture);
            AssetDatabase.GenerateUniqueAssetPath(RootFolder);
            var spritePath = folderPath + "/spritesheet.png";
            File.WriteAllBytes(spritePath, data);

            AssetDatabase.ImportAsset(spritePath, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate);

            var spriteGuid = AssetDatabase.AssetPathToGUID(spritePath);
            var importer   = (TextureImporter)AssetImporter.GetAtPath(spritePath);
            importer.textureType      = TextureImporterType.Sprite;
            importer.spriteImportMode = SpriteImportMode.Multiple;
            importer.spritesheet      = new SpriteMetaData[] { new SpriteMetaData()
                                                               {
                                                                   name = "topleft", pivot = Vector2.zero, rect = new Rect(0, 0, 16, 16)
                                                               },
                                                               new SpriteMetaData()
                                                               {
                                                                   name = "botright", pivot = Vector2.zero, rect = new Rect(16, 16, 16, 16)
                                                               } };
            importer.SaveAndReimport();
        }

        {
            var texture = new Texture2D(32, 32);
            var data    = ImageConversion.EncodeToPNG(texture);
            UnityEngine.Object.DestroyImmediate(texture);

            var spritePath = folderPath + "/sprite.png";
            File.WriteAllBytes(spritePath, data);
            AssetDatabase.ImportAsset(spritePath, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate);

            var spriteGuid = AssetDatabase.AssetPathToGUID(spritePath);
            var importer   = (TextureImporter)AssetImporter.GetAtPath(spritePath);
            importer.textureType = TextureImporterType.Sprite;
            importer.SaveAndReimport();

            string atlasPath = folderPath + "/atlas.spriteatlas";
            var    sa        = new SpriteAtlas();
            AssetDatabase.CreateAsset(sa, atlasPath);
            sa.Add(new UnityEngine.Object[]
            {
                AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(AssetDatabase.GUIDToAssetPath(spriteGuid))
            });
            SpriteAtlasUtility.PackAtlases(new SpriteAtlas[] { sa }, EditorUserBuildSettings.activeBuildTarget, false);
        }

        var folderEntry = settings.CreateOrMoveEntry(AssetDatabase.AssetPathToGUID(folderPath), group, false, false);

        folderEntry.address = "folderEntry";
    }
Ejemplo n.º 10
0
        public static void GenSpriteAtlas()
        {
            var addressGroupConfig = AssetDatabase.LoadAssetAtPath <BundleGroups>(BundleGroupConfigPath);

            if (addressGroupConfig)
            {
                var atlasItems = addressGroupConfig.SpriteAtlasItems;
                EditorUtility.DisplayProgressBar("图集", "生成图集中", 0);
                List <string> spriteAtlasKeys = new List <string>();
                foreach (var item in atlasItems)
                {
                    var assets = item.GetAllAssets();
                    foreach (var path in assets)
                    {
                        var atlasFileName = path + ".spriteatlas";
                        if (Directory.GetDirectories(path).Length == 0)
                        {
                            if (!File.Exists(atlasFileName))
                            {
                                var obj = AssetDatabase.LoadMainAssetAtPath(path);
                                if (obj)
                                {
                                    SpriteAtlas spriteAtlas = new SpriteAtlas();
                                    spriteAtlas.Add(new UnityEngine.Object[] { obj });
                                    AssetDatabase.CreateAsset(spriteAtlas, atlasFileName);
                                }
                            }
                        }

                        var atlas = AssetDatabase.LoadAssetAtPath <SpriteAtlas>(atlasFileName);
                        if (atlas)
                        {
                            if (!spriteAtlasKeys.Contains(atlasFileName))
                            {
                                spriteAtlasKeys.Add(atlasFileName);
                            }
                            else
                            {
                                Debug.LogError("重复的图集名称,解决办法:文件夹名字不重复,即使在不同的文件夹!");
                            }

                            atlas.SetIncludeInBuild(false);
                            SpriteAtlasPackingSettings settings = SpriteAtlasExtensions.GetPackingSettings(atlas);
                            settings.enableTightPacking = false;
                            settings.enableRotation     = false;
                            settings.padding            = 2;
                            SpriteAtlasExtensions.SetPackingSettings(atlas, settings);
                        }
                    }
                }
                EditorUtility.DisplayProgressBar("图集", "Packing sprite atlas", 0.7f);
                SpriteAtlasUtility.PackAllAtlases(EditorUserBuildSettings.activeBuildTarget);
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();
                EditorUtility.ClearProgressBar();
            }
        }
Ejemplo n.º 11
0
        public SpriteAtlas SetUpSpriteAtlas(int numAtlasObjects, out List <Object> subAssets)
        {
            // Setup Sprite data
            var texture = new Texture2D(32, 32);
            var data    = ImageConversion.EncodeToPNG(texture);

            UnityEngine.Object.DestroyImmediate(texture);

            // Setup Sprites
            subAssets = new List <Object>();
            Directory.CreateDirectory(ConfigFolder + "/test");
            var atlasPath = ConfigFolder + "/test" + "/testAtlas.spriteatlas";
            var newAtlas  = new SpriteAtlas();
            var sprites   = new Object[numAtlasObjects];

            for (int i = 0; i < numAtlasObjects; i++)
            {
                // Create Sprite asset
                AssetDatabase.GenerateUniqueAssetPath(ConfigFolder);
                var newSpritePath = ConfigFolder + "/test" + "/testSprite" + i + ".png";
                File.WriteAllBytes(newSpritePath, data);

                AssetDatabase.ImportAsset(newSpritePath, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate);
                var importer = (TextureImporter)AssetImporter.GetAtPath(newSpritePath);
                importer.textureType      = TextureImporterType.Sprite;
                importer.spriteImportMode = SpriteImportMode.Multiple;
                importer.spritesheet      = new SpriteMetaData[] { new SpriteMetaData()
                                                                   {
                                                                       name = "topleft", pivot = Vector2.zero, rect = new Rect(0, 0, 16, 16)
                                                                   },
                                                                   new SpriteMetaData()
                                                                   {
                                                                       name = "testSprite" + i, pivot = Vector2.zero, rect = new Rect(16, 16, 16, 16)
                                                                   } };
                importer.SaveAndReimport();

                // Add sprite to subassets
                Object spr = AssetDatabase.LoadAssetAtPath(newSpritePath, typeof(Sprite));
                spr.name   = "testSprite" + i;
                sprites[i] = spr;
                subAssets.Add(spr);
            }
            // Setup Atlas
            newAtlas.Add(sprites);
            AssetDatabase.CreateAsset(newAtlas, atlasPath);
            AssetDatabase.Refresh();
            SpriteAtlasExtensions.Add(newAtlas, sprites);
            SpriteAtlasUtility.PackAtlases(new SpriteAtlas[] { newAtlas }, EditorUserBuildSettings.activeBuildTarget, false);

            var atlasGuid = AssetDatabase.AssetPathToGUID(atlasPath);

            Settings.CreateOrMoveEntry(atlasGuid, Settings.groups[0]);

            return(newAtlas);
        }
Ejemplo n.º 12
0
        void AutoSetAtlasContents(string texturePath)
        {
            // 设置参数 可根据项目具体情况进行设置
            SpriteAtlasPackingSettings packSetting = new SpriteAtlasPackingSettings()
            {
                blockOffset        = 1,
                enableRotation     = false,
                enableTightPacking = false,
                padding            = 2,
            };
            SpriteAtlasTextureSettings textureSetting = new SpriteAtlasTextureSettings()
            {
                readable        = false,
                generateMipMaps = false,
                sRGB            = true,
                filterMode      = FilterMode.Bilinear,
            };
            TextureImporterPlatformSettings platformSetting = new TextureImporterPlatformSettings()
            {
                maxTextureSize      = 2048,
                format              = TextureImporterFormat.Automatic,
                crunchedCompression = true,
                textureCompression  = TextureImporterCompression.Compressed,
                compressionQuality  = 50,
            };
            DirectoryInfo root = new DirectoryInfo(texturePath);

            DirectoryInfo[] dirs = root.GetDirectories();
            foreach (DirectoryInfo dir in dirs)
            {
                SpriteAtlas atlas = new SpriteAtlas();
                atlas.SetPackingSettings(packSetting);
                atlas.SetTextureSettings(textureSetting);
                atlas.SetPlatformSettings(platformSetting);

                // 这里我使用的是png图片,已经生成Sprite精灵了
                FileInfo[] files = dir.GetFiles("*.png");
                foreach (FileInfo file in files)
                {
                    string dirName = Path.GetFileName(file.DirectoryName);
                    string texPath = $"{texturePath}/{dirName}/{file.Name}";
                    atlas.Add(new[] { AssetDatabase.LoadAssetAtPath <Sprite>(texPath) });
                    //Debug.Log($"Create sprite {texPath}");
                }
                string atlasPath = $"{texturePath}/{dir.Name}.spriteatlas";
                //Debug.Log($"Create sprite {atlasPath}");
                AssetDatabase.CreateAsset(atlas, atlasPath);
                AssetDatabase.SaveAssets();
            }
            // 2、添加文件夹
            //Object obj = AssetDatabase.LoadAssetAtPath(texturePath, typeof(Object));
            //atlas.Add(new[] {obj});
        }
        protected string CreateSpriteAtlas(string atlasPath, string[] spriteTextureGuids)
        {
            var sa = new SpriteAtlas();

            AssetDatabase.CreateAsset(sa, atlasPath);
            Object[] targetObjects = spriteTextureGuids.Select(g => AssetDatabase.LoadAssetAtPath <Object>(AssetDatabase.GUIDToAssetPath(g))).ToArray();
            sa.Add(targetObjects);
            SpriteAtlasUtility.PackAtlases(new SpriteAtlas[] { sa }, EditorUserBuildSettings.activeBuildTarget, false);

            AssetDatabase.Refresh();
            return(AssetDatabase.AssetPathToGUID(atlasPath));
        }
    static string CreateSpriteAtlas(string name, string guidTargetTexture)
    {
        var sa            = new SpriteAtlas();
        var targetObjects = new UnityEngine.Object[] { AssetDatabase.LoadAssetAtPath <Texture>(AssetDatabase.GUIDToAssetPath(guidTargetTexture)) };

        sa.Add(targetObjects);
        string saPath = $"{TempPath}/{name}.spriteAtlas";

        AssetDatabase.CreateAsset(sa, saPath);
        AssetDatabase.Refresh();
        return(AssetDatabase.AssetPathToGUID(saPath));
    }
        public void AddSprites(IEnumerable <Sprite> sprites)
        {
            if (m_SpriteAtlas != null && sprites.Any())
            {
                m_SpriteAtlas.Add(sprites.ToArray());

                // Add our marker and force it to be updated
                var marker = FindSpriteAtlasMarker();
                if (marker != null)
                {
                    m_SpriteAtlas.Add(new Sprite[1] {
                        FindSpriteAtlasMarker()
                    });

                    // This sucks but we have to force our marker to be re-imported
                    // This causes the sprite atlas to be updated
                    var markerPath = AssetDatabase.GetAssetPath(marker);
                    AssetDatabase.ImportAsset(markerPath, ImportAssetOptions.ForceUpdate);
                }
            }
        }
        void CreateSpriteAtlas(string path, string[] spriteAssetPaths)
        {
            var sa = new SpriteAtlas();

            AssetDatabase.CreateAsset(sa, path);
            foreach (string spritePath in spriteAssetPaths)
            {
                sa.Add(new UnityEngine.Object[]
                {
                    AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(spritePath)
                });
            }
            SpriteAtlasUtility.PackAtlases(new SpriteAtlas[] { sa }, EditorUserBuildSettings.activeBuildTarget, false);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 重新设置对应目录下的SpriteAtlas
        /// </summary>
        /// <param name="assetPath"></param>
        static private void CheckSpriteAtlas(string assetPath)
        {
            if (!assetPath.StartsWith(PathTool.ImagesDir) || assetPath.Contains(AssetBundleDefined.NO_PACK_PATH_NAME))
            {
                return;
            }
            DirectoryInfo dirInfo       = new DirectoryInfo(assetPath); // 资源路径
            DirectoryInfo parentDirInfo = dirInfo.Parent;               // 资源父路径

            if (!parentDirInfo.Exists)
            {
                return;
            }
            // 检查当前目录图集是否已存在
            foreach (var item in parentDirInfo.GetFileSystemInfos())
            {
                if (item.Name == "SpriteAtlas.spriteatlas")
                {
                    //unity下的操作的路径
                    string unityPath = item.FullName.Replace('\\', '/');          //反斜杠替换成斜杠
                    AssetDatabase.DeleteAsset(unityPath.Substring(unityPath.IndexOf("Assets")));
                }
            }

            SpriteAtlas atlas = new SpriteAtlas();

            // 图集设置
            SpriteAtlasPackingSettings packingSettings = atlas.GetPackingSettings();

            packingSettings.padding            = 4; //图片之间的间距
            packingSettings.enableTightPacking = false;
            atlas.SetPackingSettings(packingSettings);

            FileInfo fileInfo = new FileInfo(assetPath);

            // 这里我使用的是png图片,已经生成Sprite精灵了
            foreach (var item in parentDirInfo.GetFileSystemInfos())
            {
                FileInfo info = item as FileInfo;
                if (info is FileInfo && info.Extension == ".png")
                {
                    //unity下的操作的路径
                    string unityPath = item.FullName.Replace('\\', '/');          //反斜杠替换成斜杠
                    Object obj       = AssetDatabase.LoadAssetAtPath <Sprite>(unityPath.Substring(unityPath.IndexOf("Assets")));
                    atlas.Add(new[] { obj });
                }
            }
            AssetDatabase.CreateAsset(atlas, assetPath.Substring(0, assetPath.Length - fileInfo.Name.Length) + AssetBundleDefined.SPRITE_ATLAS_NAME);
        }
Ejemplo n.º 18
0
        private void TrySetupSpriteAtlas()
        {
            if (_atlas == null)
            {
                return;
            }

            Object[] atPath  = AssetDatabase.LoadAllAssetsAtPath(assetPath);
            Sprite[] sprites = atPath.Where(p => p is Sprite).Cast <Sprite>().ToArray();

            //remove existing
            _atlas.Remove(_atlas.GetPackables());

            //add sorted sprites
            Object[] inputSprites = sprites.Distinct().OrderBy(p => p.name).Cast <Object>().ToArray();
            _atlas.Add(inputSprites);
        }
Ejemplo n.º 19
0
    /// <summary>
    /// 生成一个SpriteAtlas
    /// </summary>
    /// <param name="dictory"></param>
    private static void BuildSpriteAtlas(DirectoryInfo dictory)
    {
        var         spriteAtlasName = SpriteAtlasPath + "/" + dictory.Name + "_Atlas.spriteAtlas";
        SpriteAtlas spriteAtlas     = AssetDatabase.LoadAssetAtPath <SpriteAtlas>(spriteAtlasName);

        if (null == spriteAtlas)
        {
            spriteAtlas = new SpriteAtlas();
            spriteAtlas.SetIncludeInBuild(false);
            var packingSettings = spriteAtlas.GetPackingSettings();
            packingSettings.enableRotation     = false;
            packingSettings.enableTightPacking = false;
            spriteAtlas.SetPackingSettings(packingSettings);
            var path      = DataPathToAssetPath(dictory.FullName);
            var folderObj = AssetDatabase.LoadMainAssetAtPath(path);
            var objectArr = new Object[] { folderObj };
            spriteAtlas.Add(objectArr);
            AssetDatabase.CreateAsset(spriteAtlas, spriteAtlasName);
        }
    }
Ejemplo n.º 20
0
    private void createSpriteAltas(string altasFolderPath_, string altasName_)
    {
        //New altas file.
        SpriteAtlas _atlas = new SpriteAtlas();
        SpriteAtlasPackingSettings _packSetting = new SpriteAtlasPackingSettings()
        {
            blockOffset        = 1,
            enableRotation     = true,
            enableTightPacking = true,
            padding            = 2,
        };

        _atlas.SetPackingSettings(_packSetting);
        SpriteAtlasTextureSettings _textureSetting = new SpriteAtlasTextureSettings()
        {
            readable        = false,
            generateMipMaps = false,
            sRGB            = true,
            filterMode      = FilterMode.Bilinear,
        };

        _atlas.SetTextureSettings(_textureSetting);
        TextureImporterPlatformSettings _platformSetting = new TextureImporterPlatformSettings()
        {
            maxTextureSize      = _maxTextureSize,
            format              = TextureImporterFormat.Automatic,
            crunchedCompression = _crunchedCompression,
            textureCompression  = TextureImporterCompression.Compressed,
            compressionQuality  = _compressionQuality,
        };

        _atlas.SetPlatformSettings(_platformSetting);
        //Create altas file.
        AssetDatabase.CreateAsset(_atlas, altasFolderPath_ + "/" + altasName_);
        //Get folder pack with it.
        Object _folderObj = AssetDatabase.LoadAssetAtPath(altasFolderPath_, typeof(Object));

        _atlas.Add(new [] { _folderObj });
        AssetDatabase.SaveAssets();
    }
        private static void MoveSpritesToAtlas(SpriteAtlas newAtlas)
        {
            foreach (Object selectedObject in SpriteAuditorUtility.SelectedObjects)
            {
                if (selectedObject is Sprite targetSprite)
                {
                    TryToRemoveSpriteFromAnyAtlasReference(targetSprite);

                    if (newAtlas == null)
                    {
                        continue;
                    }

                    Debug.Log($"Added {targetSprite} to {newAtlas}");
                    newAtlas.Add(new[] { selectedObject });
                    EditorUtility.SetDirty(newAtlas);
                }
            }

            SpriteAuditorUtility.ClearSelection();
            SpriteAuditorUtility.SetAllDirty();
        }
Ejemplo n.º 22
0
        private void TryCloneSpriteAtlas()
        {
            SpriteAtlas atlas = _importer.Atlas;

            if (!atlas)
            {
                return;
            }

            //clone the sprite atlas asset
            SpriteAtlas newAtlas = CloneArtifact(atlas, "/Sprites");

            //clear, then re-fill the atlas with used sprites
            newAtlas.Remove(newAtlas.GetPackables());

            //add art tiles
            Object[] objects = _artTileSprites.OrderBy(p => p.name).Cast <Object>().ToArray();
            newAtlas.Add(objects);

            //pack
            SpriteAtlasUtility.PackAtlases(new [] { newAtlas }, EditorUserBuildSettings.activeBuildTarget);
        }
Ejemplo n.º 23
0
    private static void UpdateAtlas(SpriteAtlas pSpriteAtlas, IEnumerable <Object> arrObject)
    {
        Sprite[] arrSprite = new Sprite[pSpriteAtlas.spriteCount];
        pSpriteAtlas.GetSprites(arrSprite);
        pSpriteAtlas.Remove(arrSprite);

        foreach (var pObject in arrObject)
        {
            Sprite pSprite = pObject as Sprite;
            if (pSprite == null)
            {
                continue;
            }

            if (pSpriteAtlas.GetSprite(pSprite.name) == false)
            {
                Debug.Log($"{nameof(SpriteAtlasHelper)} - Added Sprite{pSprite.name} In Sprite Atlas{pSpriteAtlas.name}");
            }
            pSpriteAtlas.Add(new Object[] { pSprite });
        }

        AssetDatabase.SaveAssets();
    }
Ejemplo n.º 24
0
        /// <summary>
        /// 图片切成9块
        /// </summary>
        public static void CreateSpriteSpolt(Texture2D image)
        {
            #region  制图片 切9个小块
            //图片保存路径
            //Texture2D image = Selection.activeObject as Texture2D;
            //获取被复制的文件
            string rootPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(image));
            string path     = rootPath + "/" + image.name + ".jpg";                         //图片路径名称

            TextureImporter rootTexture = AssetImporter.GetAtPath(path) as TextureImporter; //获取图片入口
            rootTexture.textureType = TextureImporterType.Sprite;

            AssetDatabase.ImportAsset(path, ImportAssetOptions.Default);

            string ImgName = image.name;
            //Debug.Log(image.width);
            //Debug.Log(image.height);

            string SpriteSaveFilePath = AppSetting.BundleArtResDir + AppSetting.UIAtlasDir + ImgName + "/";
            //创建图片文件夹
            ToolsHelper.CreateDir(SpriteSaveFilePath, true);
            //生成的文件
            string fileName      = ImgName + ".jpg";
            string fileNameSpile = ImgName + "_Spilt.jpg";
            //string FileNamePath = System.IO.Path.Combine(Path.GetDirectoryName(SpriteSaveFilePath), fileName);
            string fileNameSpilePath = System.IO.Path.Combine(Path.GetDirectoryName(SpriteSaveFilePath), fileNameSpile);
            //复制2份文件导目标文件夹
            //AssetDatabase.CopyAsset(path, FileNamePath);
            AssetDatabase.CopyAsset(path, fileNameSpilePath);
            //第一张图片设置成UI界面引用的图
            //TextureImporter texImp = AssetImporter.GetAtPath(FileNamePath) as TextureImporter;//获取图片入口
            //texImp.textureType = TextureImporterType.Sprite;
            //texImp.spriteImportMode = SpriteImportMode.Single;
            //第2张图切9个小块
            TextureImporter texImp = AssetImporter.GetAtPath(fileNameSpilePath) as TextureImporter;//获取图片入口


            //获取图片的宽高
            int width  = image.width;
            int height = image.height;
            //单位框高
            int tempWidth  = width / 3;
            int tempHeight = height / 3;

            List <SpriteMetaData> spriteMetaDatas = new List <SpriteMetaData>();
            for (int y = 0; y < 3; y++)
            {
                for (int x = 0; x < 3; x++)
                {
                    SpriteMetaData metaData = new SpriteMetaData();
                    metaData.name   = image.name + "_" + (y * 3 + x);
                    metaData.pivot  = Vector2.one * 0.5f;
                    metaData.border = Vector4.zero;

                    Rect rect = new Rect();
                    rect.x        = x * tempWidth;
                    rect.y        = (2 - y) * tempHeight;
                    rect.width    = tempWidth;
                    rect.height   = tempHeight;
                    metaData.rect = rect;
                    spriteMetaDatas.Add(metaData);
                }
            }

            texImp.textureType      = TextureImporterType.Sprite;
            texImp.spriteImportMode = SpriteImportMode.Multiple;
            texImp.spritesheet      = spriteMetaDatas.ToArray();
            #endregion

            #region 创建一个图集与上一部创建的图相关联

            string AtlasSaveFilePath = AppSetting.BundleResDir + AppSetting.UIAtlasDir + ImgName + ".spriteatlas";
            if (File.Exists(AtlasSaveFilePath))
            {
                AssetDatabase.DeleteAsset(AtlasSaveFilePath);
            }
            SpriteAtlas        spriteAtlas = new SpriteAtlas();
            UnityEngine.Object obj         = AssetDatabase.LoadAssetAtPath(AppSetting.BundleArtResDir + AppSetting.UIAtlasDir + ImgName, typeof(UnityEngine.Object));
            Debug.Log(obj);
            spriteAtlas.Add(new[] { obj });
            AssetDatabase.CreateAsset(spriteAtlas, AtlasSaveFilePath);
            #endregion

            //AssetDatabase.ImportAsset(FileNamePath, ImportAssetOptions.Default);
            AssetDatabase.ImportAsset(fileNameSpilePath, ImportAssetOptions.Default);
        }
Ejemplo n.º 25
0
    static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
    {
        for (int i = 0; i < importedAssets.Length; i++)
        {
            string assetPath = importedAssets[i].Replace("\\", "/");
            if (!assetPath.StartsWith("Assets/Localization/") && !assetPath.StartsWith("Assets/Res/"))
            {
                continue;
            }
            if (!AssetDatabase.IsValidFolder(assetPath))
            {
                continue;                                          //非文件夹文件
            }
            DirectoryInfo dirAssetInfo = new DirectoryInfo(assetPath);
            for (int j = 0; j < _atlasRuleDir.Length; j++)
            {
                AtlasInfo atlasInfo_Rule = _atlasRuleDir[j];
                if (!assetPath.Equals(atlasInfo_Rule.dir) && !assetPath.StartsWith(atlasInfo_Rule.dir + "/"))
                {
                    continue;
                }
                //命中目标文件夹
                if (dirAssetInfo.Parent.FullName.Equals(atlasInfo_Rule.fullName))
                {
                    FileInfo[] atlasFiles  = dirAssetInfo.GetFiles("*.spriteatlas", SearchOption.AllDirectories);
                    FileInfo   targetAtlas = null; //文件夹下直属Atlas
                    for (int k = 0; k < atlasFiles.Length; k++)
                    {
                        FileInfo file = atlasFiles[k];
                        if (targetAtlas == null)
                        {
                            if (file.Directory.FullName.Equals(dirAssetInfo.FullName))
                            {
                                targetAtlas = file;
                            }
                        }
                        else
                        {
                            file.Delete(); //删除其他的Atlas
                        }
                    }

                    string targetName = atlasInfo_Rule.prefix_name + "_" + dirAssetInfo.Name + "_Atlas.spriteatlas";
                    if (targetAtlas == null) //没有找到直属Atlas
                    {
                        AssetDatabase.CreateAsset(new SpriteAtlas(), assetPath + "/" + targetName);
                        targetAtlas = new FileInfo(dirAssetInfo.FullName + "/" + targetName);
                    }
                    else
                    {
                        AssetDatabase.RenameAsset(assetPath + "/" + targetAtlas.Name, targetName); //改名
                        targetAtlas = new FileInfo(dirAssetInfo.FullName + "/" + targetName);
                    }
                    //对Atlas进行设置
                    SpriteAtlas atlas = AssetDatabase.LoadAssetAtPath <SpriteAtlas>(assetPath + "/" + targetAtlas.Name);
                    SpriteAtlasPackingSettings packingSettings = atlas.GetPackingSettings();
                    packingSettings.enableRotation     = atlasInfo_Rule.isRotation;
                    packingSettings.enableTightPacking = atlasInfo_Rule.isTight;
                    packingSettings.padding            = 2;
                    atlas.SetPackingSettings(packingSettings);

                    TextureImporterPlatformSettings platformSettings = atlas.GetPlatformSettings("iPhone");
                    platformSettings.overridden = true;
                    if (platformSettings.maxTextureSize > 2048)
                    {
                        platformSettings.maxTextureSize = 2048;
                    }
                    platformSettings.format = TextureImporterFormat.ASTC_RGBA_6x6;
                    atlas.SetPlatformSettings(platformSettings);

                    atlas.Remove(atlas.GetPackables());
                    atlas.Add(new [] { AssetDatabase.LoadAssetAtPath <Object>(assetPath) });
                }
                break;
            }
        }
    }
Ejemplo n.º 26
0
    static void AutoSetAtlasContents(string dir)
    {
        SpriteAtlas atlas = new SpriteAtlas();

        // 设置参数 可根据项目具体情况进行设置
        SpriteAtlasPackingSettings packSetting = new SpriteAtlasPackingSettings()
        {
            blockOffset        = 1,
            enableRotation     = false,
            enableTightPacking = false,
            padding            = 2,
        };

        atlas.SetPackingSettings(packSetting);

        SpriteAtlasTextureSettings textureSetting = new SpriteAtlasTextureSettings()
        {
            readable        = false,
            generateMipMaps = false,
            sRGB            = true,
            filterMode      = FilterMode.Bilinear,
        };

        atlas.SetTextureSettings(textureSetting);

        TextureImporterPlatformSettings platformSetting = new TextureImporterPlatformSettings()
        {
            maxTextureSize      = 1024,
            format              = TextureImporterFormat.Automatic,
            crunchedCompression = true,
            textureCompression  = TextureImporterCompression.Compressed,
            compressionQuality  = 50,
        };

        atlas.SetPlatformSettings(platformSetting);

        DirectoryInfo dirInfo = new DirectoryInfo(dir);
        string        path    = $"{dir}/{dirInfo.Name}.spriteatlas";

        if (File.Exists(path))
        {
            File.Delete(path);
        }

        AssetDatabase.CreateAsset(atlas, path);

        //1.添加文件
        FileInfo[] files = dirInfo.GetFiles("*.png");
        foreach (FileInfo file in files)
        {
            atlas.Add(new[] { AssetDatabase.LoadAssetAtPath <Sprite>($"{dir}/{file.Name}") });
        }

        //2.添加子文件夹
        DirectoryInfo[] subdirs = dirInfo.GetDirectories();
        foreach (DirectoryInfo subdir in subdirs)
        {
            Object obj = AssetDatabase.LoadAssetAtPath(subdir.FullName, typeof(Object));
            atlas.Add(new[] { obj });
        }

        AssetDatabase.SaveAssets();
        Debug.LogFormat("Generate a <b>{0}.spriteatlas</b> success! path=<b>{1}</b>",
                        dirInfo.Name, path);
    }