[Resolved]Sprite Slicing At Runtime - Error

Hey,

I’m slicing sprites at runtime and I have this weird issue were if I slice to many times I get an error saying cannot create sprite.

I’m taking an already loaded texture and breaking it down by column/width amounts. On most image I load, when I get to 10 or more splits, that’s when the error occurs.

Here is the example error:

ArgumentException: Could not create sprite (0, 115.2, 96, 12.8) from a 96x128 texture.

And here is a snip of the code slicing:

public void UpdateSlices()
{
    sliceSprites = new List<Sprite>();
    float columnWidth = graphicImorted.sprite.texture.width / xSlider.value;
    float rowHeight = graphicImorted.sprite.texture.height / ySlider.value;

    float yOffset = 0;
    float xOffset = 0;
    for (int y = 0; y < ySlider.value; y++)
    {
        for (int x = 0; x < xSlider.value; x++)
        {
            Sprite sprite = Sprite.Create(graphicImorted.sprite.texture, new Rect(xOffset, yOffset, columnWidth, rowHeight), Vector2.One / 2, 100f);
            sliceSprites.Add(sprite);
            xOffset += columnWidth;
        }
        yOffset += rowHeight;
        xOffset = 0;
    }
}

To me the math looks solid, but by the error it seams to say its trying to slice an area that’s out of bounds.

Any help would be appreciated :slight_smile:

So that maths was right, in real world. But I forgot to consider the limitations of Floats. Changed and casted with Longs resolved the issue :slight_smile:

please make edited script , i need tha sprite slicing at runtime for my game

1 Like

From memory it was just replacing the floats to longs…

long columnWidth = graphicImorted.sprite.texture.width / xSlider.value;
long rowHeight = graphicImorted.sprite.texture.height / ySlider.value;
long yOffset = 0;
long xOffset = 0;

Its because the float can only store so many intervals, and when iterating through them a little bit gets cut of each time.

Just replace graphicImorted with your reference sprite, and store the slices in a list like at the top of mine sliceSprites. columnWidth and rowHeight and be declared any way you need.

Good luck :slight_smile:

thanks for your answer but what iwant is something like " sprite that has been sliced " in png format , imean , idont want to make new game object and make it as child at runtime :cry: