Unity3D Sprite(精灵)分割

时间:2021-08-19 23:32:59

思路很low,把贴图分开成两张贴图再创建两个精灵将贴图覆盖上去,因为一直没做过2D的东西,发现查缺补漏的地方还不少,记录下。


这里只简单的分了上下两片

void Cut(Vector3 a, Vector3 b)
    {
        if (oriSR == null)
            oriSR = transform.GetComponent<SpriteRenderer>();

        Texture2D textureSP = oriSR.sprite.texture;
        Texture2D texUL, texDR;
        int texX, texY;
        texX = textureSP.width;
        texY = textureSP.height;

        texUL = new Texture2D(textureSP.width, textureSP.height);
        texDR = new Texture2D(textureSP.width, textureSP.height);

        print(textureSP.GetPixel(1000, 400) + " " +  textureSP.GetPixel(400,1000));
        for (int x = 0; x < texX; x++)
        {
            for (int y = 0; y < texY; y++)
            {
                if (y > texY/2)
                {
                    texUL.SetPixel(x, y, textureSP.GetPixel(x,y));
                    texDR.SetPixel(x, y, Color.clear);
                }
                else
                {
                    texDR.SetPixel(x, y, textureSP.GetPixel(x, y));
                    texUL.SetPixel(x, y, Color.clear);
                }
            }
        }

        texUL.Apply();
        texDR.Apply();
        NewSprite(texUL);

        NewSprite(texDR);
    }


上面代码重点记录两个东西,第一,贴图需要在Advanced中改为可读,第二贴图处理完成后要Apply,下次不要在这耽误时间了。



下面为精灵的创建方法,主要就是Sprite.Create花了好长时间

    GameObject NewSprite(Texture2D tex)
    {
        GameObject spriteC = Instantiate(transform.gameObject);
        spriteC.GetComponent<SpriteRenderer>().sprite= Sprite.Create(tex,new Rect(0,0,tex.width,tex.height),Vector2.zero);
        return null;
    }