Take the 2-minute tour ×

I am trying to make like an eraser tool (when the user drags the finger on a texture,the texture becomes transparent on that place). I tried this using the code below (i found an example online and modified it a bit), but it is too slow. I am using a brush texture to draw on the background texture.. Is there another solution to this problem? Maybe it would be quicker using some shader but I don't know how.

Thanks for any help

void Start()
   stencilUV = new Color[stencil.width * stencil.height];
   tex = (Texture2D)Instantiate(paintMaterial.mainTexture);

void Update () 
     RaycastHit hit;
    if (Input.touchCount == 0) return;
    //if (!Input.GetMouseButton(0)) return;
    if (Physics.Raycast(mainCamera.ScreenPointToRay(Input.mousePosition), out hit))
        pixelUV = hit.textureCoord;
        pixelUV.x *= tex.width;
        pixelUV.y *= tex.height;

        CreateStencil((int)pixelUV.x, (int)pixelUV.y, stencil);

void CreateStencil(int x, int y, Texture2D texture)
    paintMaterial.mainTexture = tex;
    for (int xPix = 0; xPix<texture.width; xPix++)
        for (int yPix=0;yPix<texture.height; yPix++)
            stencilUV[i] = tex.GetPixel((x - texture.width / 2) + xPix,
                (y - texture.height / 2) + yPix);
            stencilUV[i].a = 0;//1-color.a;
    tex.SetPixels(x-texture.width/2, y-texture.height/2, texture.width, texture.height, stencilUV);
share|improve this question
add comment

1 Answer

well as you know, the Update() function gets called every frame. So this is the place where you should try to optimize your code. The CreateStencil() function seems pretty expensive to me, as you iterate over every pixel in the texture and then call tex.GetPixel(..) inside your for loops - this means: when you touch the screen the app tries to run every frame this function for every pixel in your texture - definitely not the way to go. I would try to buffer the pixel information in some other array in the Start() or Awake() function and do only the necessary parts inside Update(). Every expensive opertation you can leave out there is crucial for making your app run smooth on the iPhone.

share|improve this answer
add comment

Your Answer


