Fatal Error-Too many heap sections while texture painting

My code runs very smooth for texture painting onto a model for about 30 minutes or so, but then it starts lagging horribly, locks up, and shuts down giving a message of “Fatal Error-Too many heap sections” or something very similar. I’ve tried destroying the texture after updating it to conserve the ram (via some other heap errors I’ve found relating to this), but the error seems to keep occurring.

Is there a better way to do this than what I have here? Is there a garbage collection solution that I may use to fix this? I’ve been working on this problem for about 2 weeks straight trying to figure it out before posting here.

Thanks for your time and any solutions.

void Update(){
if(Input.GetMouseButton(0))
{
   if(hit.transform == transform && stillPosition!=hit.textureCoord)
   {							
     AirPixels(thisTexture.GetPixel((int) (hit.textureCoord.x*thisTexture.width), (int)(hit.textureCoord.y*thisTexture.height)), hit.textureCoord);				
	updateTex=true;
					
	}
  }
}

void AirPixels(Color theColor, Vector2 pixCoord)
	{		
		Vector2 pCoord = pixCoord;
		pixCoord.x *= thisTexture.width;
		pixCoord.y *= thisTexture.height;
		float minX = pixCoord.x- brushWidth;
		float maxX = pixCoord.x + brushWidth;
		float minY = pixCoord.y  - brushWidth;
		float maxY = pixCoord.y  + brushWidth;
		
		for(float x=minX; x<=maxX; x++)
		{
			for(float y =minY; y <= maxY; y++)
			{				
				Vector2 p = new Vector2(x, y);
				p-= pixCoord;
				if(Mathf.FloorToInt(p.magnitude)>=brushWidth)
					continue;
				float	shade = brushWidth - p.magnitude;	
				thisTexture.SetPixel((int)x, (int)y, Color.Lerp(thisTexture.GetPixel((int)x, (int)y), selectedColor, (airStrength *.01f)*shade));				
			
			}				
		}		
		thisTexture.wrapMode=TextureWrapMode.Clamp;
		thisTexture.Apply();				
	}//end of AirPixels()

Dont’s use GetPixel / SetPixel unless you really need to work on a single pixel. As soon as you work on more than one use GetPixels / SetPixels. You would use GetPixels once in Start and then work on the color array. GetPixel as well as SetPixel will lock and release the texture everytime you call those methods.

To access a certain pixel within the Color array you just have to do:

int index = (int)x + ((int)y) * thisTexture.width;

It’s also recommended to cache the textures width / height in variables which can be accessed faster.