Unity切割Sprite图集转换为多张图片
生活随笔
收集整理的這篇文章主要介紹了
Unity切割Sprite图集转换为多张图片
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?為了可以使用Unity自帶的精靈切割,要將紋理類型改成"Sprite","Sprite Mode"改成"Multiple","Format"改成"Truecolor",點擊"Apply"按鈕進(jìn)行應(yīng)用。
接下來,因為要對圖片進(jìn)行讀寫操作,要更改圖片的屬性才能進(jìn)行,否則會提示如下:
UnityException: Texture 'testUI' is not readable, the texture memory can not be accessed from scripts. You can make the texture readable in the Texture Import Settings.
將圖片紋理類型更改為"Advanced",將"Read/Write Enabled"屬性進(jìn)行打勾,如下圖所示:
?
下面代碼:
[MenuItem("Tools/export select sprite", false, 51)]public static void exportSprite(){Texture2D image = Selection.activeObject as Texture2D;//獲取對象if (image != null){string tDirName = AssetDatabase.GetAssetPath(image).Replace(image.name + ".png", image.name + "") + @"/";tDirName = tDirName.Replace(@"Assets/", @"TexturePacker/"); //輸出路徑string path = Path.GetDirectoryName(AssetDatabase.GetAssetPath(image)) + "/" + image.name + ".png";//圖片路徑名稱if (Directory.Exists(tDirName) == false){Directory.CreateDirectory(tDirName);}TextureImporter texImp = AssetImporter.GetAtPath(path) as TextureImporter;foreach (SpriteMetaData metaData in texImp.spritesheet) //遍歷小圖集{Texture2D myimage = new Texture2D((int)metaData.rect.width, (int)metaData.rect.height);for (int y = (int)metaData.rect.y; y < metaData.rect.y + metaData.rect.height; y++)//Y軸像素{for (int x = (int)metaData.rect.x; x < metaData.rect.x + metaData.rect.width; x++)myimage.SetPixel(x - (int)metaData.rect.x, y - (int)metaData.rect.y, image.GetPixel(x, y));}//轉(zhuǎn)換紋理到EncodeToPNG兼容格式if (myimage.format != TextureFormat.ARGB32 && myimage.format != TextureFormat.RGB24){Texture2D newTexture = new Texture2D(myimage.width, myimage.height);newTexture.SetPixels(myimage.GetPixels(0), 0);myimage = newTexture;}var pngData = myimage.EncodeToPNG();File.WriteAllBytes(tDirName + "/" + metaData.name + ".png", pngData);}Debug.LogError("export " + image.name + " sprite finished");}}?
?
總結(jié)
以上是生活随笔為你收集整理的Unity切割Sprite图集转换为多张图片的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【推免攻略】二.联系导师的前期准备及注意
- 下一篇: 盘口技术大全(七): 拉升