Cutting a sprite - optimization

Hello, I made a script that creates a hole in a sprite, but it’s kinda slow. It takes in average 100ms to do all this, which freezes the game for those 100ms.

It basicly creates a new texture and assigns the old sprite to this new texture, and then creates the hole. Then applies and sends the texture to the objects sprite.

Here’s the code:

void addCircle(int range,vector3 position){     
        Texture2D texture = new Texture2D(w, h);
        GetComponent<Renderer>().material.mainTexture = texture;
        texture = spr.sprite.texture;


        int x1 =  Mathf.RoundToInt (    Mathf.Max(0,position.x-range)        );
        int y1 =  Mathf.RoundToInt (    Mathf.Max(0,position.y-range)        );
        int x2 =  Mathf.RoundToInt (    Mathf.Min(position.x+range,w)        );
        int y2 =  Mathf.RoundToInt (    Mathf.Min(position.y+range,h)        );

        for (int y = y1; y < y2; y++) {
            for (int x = x1; x < x2; x++) {
                if(Vector2.Distance(new Vector2(position.x,position.y),new Vector2(x,y)) <= range){
                    Color color = texture.GetPixel (x, y);
                    color.a = 0;
                    texture.SetPixel(x, y, color);
                }

            }
        }

        texture.Apply();
        spr.sprite = Sprite.Create(texture,new Rect(0,0,w,h),new Vector2(0.5f,0.5f));

        Destroy (this.gameObject.GetComponent<PolygonCollider2D> ());
        this.gameObject.AddComponent<PolygonCollider2D> ();
    }

I ran a stopwatch and the operations that took the most time to finish was the addComponent and the texture.Apply.

Does anyone know how I can improve this script to make it faster?

Thanks for your time!

Another victim of Distance… Instead of your Vector2.Distance line, you should square your range and use:

if (new Vector2(position.x - x, position.y - y).sqrMagnitude <= sqrRange) {

PolygonCollider2D is probably slow because it has to build a new collider for your sprite.

Is there any other way to handle collisions without polygon collider? because the other colliders don’t seem to work with these shapes =\

Thanks for the answer!