untiy 图集(altas)切除精灵

作者: bde04638cca8 | 来源:发表于2016-10-11 11:12 被阅读169次

    最近开始学习unity,很多东西学习过了,很久不用又给忘记了,所以写一个笔记记录下。这里讲的untiy自带的工具,没有用到NGUI的切图。

    1.第一步,先将图集导入到Resources目录下,没有创建一个哈。最好是Resources/Sprites,这个sprites文件夹随便你取,但是一定要在Resources这个目录下的。(题外话,profab也得在Resources这个目录下,要不加载代码Instances不出来,这都是我自己走过的坑)
    2.第二步,在Inspector中设置图片类型为Sprite,Sprite Mode设置为Multiple,Format 设置成Truecolor。ok,点开SpriteEditor。

    Inspector.png

    3.第三步,在SpriteEditor视图中,点击左上角的"Slice"按钮,弹出切片设置,再次点击里面的"Slice"按钮,就会自动对图片进行切割.
    在对切割不完整的地方进行修正后,点击右上角的"Apply"按钮,进行保存。可以看到Project视图下这个图集,已经被分割出许多小图了.

    如果还有进一步需求的话,比喻说切出来的图集名称是xx_01,使用的时候看着很古怪,还可以把图片一张一张的切出来,随便你修改名称了。

    4.把做好的图集,texture type 设置成Advance ,并且把read/write勾上,然后把他放在Resources的目录下。好了,准备工作都做好了,现在开始切成一张张的sprite,然后把这段代码绑定在Camera上就行了。运行的时候,点Tools/导出精灵,over。

    using UnityEngine;
    using UnityEditor;
    
    public class SlicePic: MonoBehaviour
    {
    [MenuItem("Tools/导出精灵")]
    static void SaveSprite()
    {
    string resourcesPath = "Assets/Resources/";
    foreach (Object obj in Selection.objects)
    {
    string selectionPath = AssetDatabase.GetAssetPath(obj);
    
    // 必须最上级是"Assets/Resources/"
    if (selectionPath.StartsWith(resourcesPath))
    {
    string selectionExt = System.IO.Path.GetExtension(selectionPath);
    if (selectionExt.Length == 0)
    {
    continue;
    }
    
    // 从路径"Assets/Resources/UI/testUI.png"得到路径"UI/testUI"
    string loadPath = selectionPath.Remove(selectionPath.Length - selectionExt.Length);
    loadPath = loadPath.Substring(resourcesPath.Length);
    
    // 加载此文件下的所有资源
    Sprite[] sprites = Resources.LoadAll<Sprite>(loadPath);
    if (sprites.Length > 0)
    {
    // 创建导出文件夹
    string outPath = Application.dataPath + "/outSprite/" + loadPath;
    System.IO.Directory.CreateDirectory(outPath);
    
    foreach (Sprite sprite in sprites)
    {
    // 创建单独的纹理
    Texture2D tex = new Texture2D((int)sprite.rect.width, (int)sprite.rect.height, sprite.texture.format, false);
    tex.SetPixels(sprite.texture.GetPixels((int)sprite.rect.xMin, (int)sprite.rect.yMin,
    (int)sprite.rect.width, (int)sprite.rect.height));
    tex.Apply();
    
    // 写入成PNG文件
    System.IO.File.WriteAllBytes(outPath + "/" + sprite.name + ".png", tex.EncodeToPNG());
    }
    Debug.Log("SaveSprite to " + outPath);
    }
    }
    }
    Debug.Log("SaveSprite Finished");
    }
    }
    

    相关文章

      网友评论

        本文标题:untiy 图集(altas)切除精灵

        本文链接:https://www.haomeiwen.com/subject/pizvyttx.html