modify texture at runtime with setpixels

I’m tryint to modify a small part of the texture at runtime using SetPixels. I think I need to get the pixel block first than modify the color afterward, but it doesn’t work when i apply the following code. Texture is set to readable and to RGB 24 bit.

var tex : Texture2D = renderer.material.mainTexture as Texture2D;
var pixelUV = hit.textureCoord;

valx = pixelUV.x * 100;
valy = pixelUV.y * 100;

pixelUV.x *= tex.width;
pixelUV.y *= tex.height;
var intx:int = pixelUV.x;
var inty:int = pixelUV.y;

var colors = new Color[3];
colors[0] = Color.white;
colors[1] = Color.black;
colors[2] = Color.blue;

tex.GetPixels(0,0,100,100);
tex.SetPixels(0,0,100,100,colors);

tex.Apply();

I’m expecting to change 100 pixels at location x0, y0, but nothing happens. The examples from Unity Script works but is kind of confusing.

There are two potential roots:

  1. is the texture marked for getpixel / setpixel modification on import? otherwise you can’t alter it at all.
  2. Also, your array is not 100*100 colors long, which means its incorrect. As the documentation on this function mentions, the colors array must have the same amount of pixels stored as the area you paint, you can’t use a single color for “rect fill”
  1. I set it as readable so it should work.
  2. Still not quite sure how colors work, but hopefully it’ll work without changing the mip level. I thought the block means the number of pixels I want to change color.

function SetPixels (x : int, y : int, blockWidth : int, blockHeight : int, colors : Color[ ], miplevel : int = 0) : void

Thats correct, but your colors array is Color[3]
But it needs to be Color[100*100] or whatever you specify as block size

works now, thanks.

var colors = new Color[100*100];

for(var i = 0; i < 100*100; i++)
colors = Color.white;
tex.GetPixels(500,500,100,100);
tex.SetPixels(500,500,100,100,colors);
tex.Apply();

fred,

Assume that you have multiple cube objects with the same texture and you want to modify the texture of only one cube object.
How to do it?

You need a different material and a different texture for each cube object in order to do this.