Unity3d-帮助,这个代码在iPhone上太慢了



我正试图制作一个类似橡皮擦的工具(当用户在纹理上拖动手指时,该纹理在该位置变得透明)。我用下面的代码尝试了一下(我在网上找到了一个例子,并对它进行了一些修改),但速度太慢了。我正在使用笔刷纹理在背景纹理上绘制。。这个问题还有别的解决办法吗?也许使用一些着色器会更快,但我不知道怎么做。

感谢的帮助

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;
            i++;
        }
    }
    i=0;
    tex.SetPixels(x-texture.width/2, y-texture.height/2, texture.width, texture.height, stencilUV);
    tex.Apply();
}

正如您所知,Update()函数在每帧都会被调用。因此,这是您应该尝试优化代码的地方。CreateStencil()函数对我来说似乎相当昂贵,因为你迭代纹理中的每个像素,然后在for循环中调用tex.GetPixel(..)——这意味着:当你触摸屏幕时,该应用程序会尝试为纹理中的每个像素运行每一帧该功能——这绝对不是一种方法。我会尝试在Start()Awake()函数中的其他数组中缓冲像素信息,并只在Update()中执行必要的部分。你可以省去的每一项昂贵的操作都对让你的应用程序在iPhone上平稳运行至关重要。

最新更新