how to edit sprites in runtime?

Hello, I ve started to develop my first 2d game and I ve got a problem. I have a sprite of the ground and my hero can dig that ground, that means that I should edit my sprite of ground and make holes in it, so I can see my background image through these holes. Just like in game of “Worms”.
Is it possible in Unity to edit sprites in runtime?

Probably the simplest way for just one sprite is to use a rendertexture, then when you want to make a hole, ‘render’ a hole into the rendertexture. Then have a sprite or quad or cube or something with a material with the rendertexture on it, to draw it to the screen with a separate camera. This does limit you to the maximum texture size for your environment but it’s very fast. Your next question will probably be collision detection… either you have to figure out a method yourself or if you want proper sprite colliders etc you’ll need to regenerate the sprite’s collision mesh from script.

1 Like

other way to change sprite

public Sprite[] spr;
    SpriteRenderer sr;

    void Start () {
        sr = GetComponent <SpriteRenderer>();
        //something from array or resource.load
        sr.sprite = spr [1];
    }

or you can make it with animation state.

And as imaginaryhuman said: "Your next question will probably be collision detection… " :smile:

I think, I whould make this game from many “ready to use cells”. And then just switch them depended on game state.