Texture2D.SetPixel() crashes

Hi,

I am trying to draw a label with a texture2d that I am suppose to color according to user input. But it crashes every time after a few seconds…

This is the code:

//--------------------------------------------------
color = RGBLabelSlider(new Rect(10, 10, 200, 30), color);
texture = new Texture2D(100, 100);
renderer.material.mainTexture = texture;
for (int i = 0; i < 100; i++)
for (int j = 0; j < 100; j++)
texture.SetPixel(i, j, color);

GUI.Label(new Rect(1000, 550, 100, 100), new GUIContent(texture));
texture.Apply();
//--------------------------------------------------

Where RGBLabelSlider() is the function described in CompoundControls tutorial in the Unity Scripting Guide.

This piece of code is inside OnGUI(), in a script that’s attached to the main camera. Also, the main camera has a mesh renderer (or else this line: “renderer.material.mainTexture = texture;” would fail).
color and texture are private members of this script.

This code is crashing unity altogether, so I don’t have access to the console for debugging.

Does anyone have any ideea why this happens?

remove the renderer line.
You don’t need it at all as you don’t want to assign the texture to any 3d model from what I’m getting.

Also you are actually missing the one and most important step: setting it does not do anything to the texture, unless you use Apply afterwards

Thanks dreamora,

I did exactly what you suggested, and it works for a minute or so, but after that it gets locked. Something like getting stuck in an infinite loop…
Anyway, I was already using texture.Apply(), after the GUI.Label(…) call.
Can anyone tell me how to color a label with a solid color? Perhaps this is not the best way to do it…

Thanks in advance

If you are calling

texture = new Texture2D(100, 100);

every time you hit OnGUI you are creating multiple Texture2D object. You need to remove the creation of this object to the Awake() funciton so it only happens once.

You will also need to do the same thing for the

new GUIContent(texture) call.

You will need to create some variable to store the objects.

var canvas : Texture2D;
var canvasContent : GUIContent;