如何统一拆分图像

How do I split an image in unity

我想用 C# 为这张图片制作动画。精灵编辑器对我不起作用,因为我希望它是一个动态系统。 如果有这方面的方法,请分享给我。

如果如您所说,所有源和目标图块图像都具有已知尺寸,您可以这样做,例如

如果您需要它们作为 Texture2Ds(更昂贵和内存密集)

public Texture2D[] SplitTextureToTextures(Texture2D source, Vector2Int tileSize)
{
    // get the source dimensions
    var sourceWidth = source.width;
    var sourceHeight = source.height;

    // Check how often the given tileSize fits into the image
    var tileAmountX = Mathf.FloorToInt(sourceWidth / (float)tileSize.x);
    var tileAmountY = Mathf.FloorToInt(sourceHeight / (float)tileSize.y);

    var output = new Texture2D[tileAmountX * tileAmountY];

    // Iterate through the tiles horizontal then vertical
    // starting at the top left tile
    for (var y = tileAmountY - 1; y >= 0; y--)
    {
        for (var x = 0; x < tileAmountX; x++)
        {
            // get the bottom left pixel coordinate of the current tile
            var bottomLeftPixelX = x * tileSize.x;
            var bottomLeftPixelY = y * tileSize.y;

            // get the pixels in the rect for this tile
            var pixels = source.GetPixels(bottomLeftPixelX, bottomLeftPixelY, tileSize.x, tileSize.y);

            // create the new texture (adjust the additional parameters according to your needs)
            var texture = new Texture2D(tileSize.x, tileSize.y, source.format, false);
                
            // write the pixels into the new texture
            texture.SetPixels(pixels);
            texture.Apply();

            // and store it in the output
            output[x + y * tileAmountX] = texture;
        }
    }

    return output;
} 

或者如果您需要 Sprites

public Sprite[] SplitTextureToSprites(Texture2D source, Vector2Int tileSize)
{
    // get the source dimensions
    var sourceWidth = source.width;
    var sourceHeight = source.height;

    // Check how often the given tileSize fits into the image
    var tileAmountX = Mathf.FloorToInt(sourceWidth / (float)tileSize.x);
    var tileAmountY = Mathf.FloorToInt(sourceHeight / (float)tileSize.y);

    var output = new Texture2D[tileAmountX * tileAmountY];

    // Iterate through the tiles horizontal then vertical
    // starting at the top left tile
    for (var y = tileAmountY - 1; y >= 0; y--)
    {
        for (var x = 0; x < tileAmountX; x++)
        {
           // get the bottom left pixel coordinate of the current tile
            var bottomLeftPixelX = x * tileSize.x;
            var bottomLeftPixelY = y * tileSize.y;

            // instead of having to get the pixel data
            // For a sprite you just have to set the rect from which part of the texture to create a sprite
            var sprite = Sprite.Create(source, new Rect(bottomLeftPixelX, bottomLeftPixelY, tileSize.x, tileSize.y), Vector2.one * 0.5f);

            output[x + y * tileAmountX] = sprite;
        }
    }

    return output;
}