Copy pixel color values to array

Hello,

I’m trying to read individual pixel values from a 1024x1024 texture to use as terrain data but Unity crashes with an Out of Memory error.

I’m using this code:

  var www : WWW = new WWW("http://ex2.localhost/heightmap.png");
  yield(www);
  var map :float[,] = new float[1024,1024];
  for (var y:int=0; y<1024;y++) {
    for (var x:int=0; x<1024;x++) {
      map[x,y] = www.texture.GetPixel(x,y).grayscale;
    }
  }

What is the correct way to do it?

I also looked into GetPixels, but individual pixel color doesn’t seem to be available.

Thanks.

Every time you do www.texture you get a new copy. Instead take a reference first:

  var www : WWW = new WWW("http://ex2.localhost/heightmap.png");
  yield www;
  var map :float[,] = new float[1024,1024];
  var tex = www.texture;
  for (var y:int=0; y<1024;y++) {
    for (var x:int=0; x<1024;x++) {
      map[x,y] = tex.GetPixel(x,y).grayscale;
    }
  }