Unity3d-帮助,此代码在iPhone上太慢

Unity3d-帮助,此代码在iPhone上太慢,unity3d,alpha,Unity3d,Alpha,我试着制作一个橡皮擦工具(当用户在纹理上拖动手指时,纹理在该位置变得透明)。我使用下面的代码进行了尝试(我在网上找到了一个示例并对其进行了一些修改),但速度太慢了。我正在使用笔刷纹理在背景纹理上绘制。。这个问题还有别的解决办法吗?也许使用一些着色器会更快,但我不知道如何使用 谢谢你的帮助 void Start() { stencilUV = new Color[stencil.width * stencil.height]; tex = (Texture2D)Instantiate(

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

谢谢你的帮助

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();
}
void Start()
{
stencilUV=新颜色[stencil.width*stencil.height];
tex=(Texture2D)实例化(paintMaterial.mainTexture);
}
无效更新()
{
雷卡斯特击中;
如果(Input.touchCount==0)返回;
//如果(!Input.GetMouseButton(0))返回;
if(Physics.Raycast(mainCamera.ScreenPointToRay(Input.mousePosition),out-hit))
{
pixelUV=hit.textureCoord;
像素UV.x*=tex.width;
像素UV.y*=像素高度;
CreateStencil((int)pixelUV.x,(int)pixelUV.y,stencil);
}
}
void CreateStencil(int x、int y、Texture2D纹理)
{
paintMaterial.mainTexture=tex;

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