Programatically creating and setting UI image
So I have an image in my ui. At the moment I am just trying to get it to be white. The code is as following:
UnityEngine.UI.Image image;
void Update () {
Color[] colors = new Color[50*200];
for(int j = 0; j < 200; j++){
for(int i = 0; i < 50; i++){
colors[i*j]= Color.white;
}
}
Texture2D t = new Texture2D(50,200);
t.SetPixels(colors);
image.sprite = Sprite.Create(t,new Rect(0,0,50,200), new Vector2(.5f,.5f));
}
I'd expect this to create a white image, but I get the following result(ignore the green object):
The pixels seem kind of scattered, and I can't get it to work right. What should i do? What am I doing wrong?
First thing is: You really shouldn't do this in the Update() function as you are creating a new Color array and Texture2D at EVERY frame. Second: Have you tried to use t.Apply() ?
Thanks for the advice! I have tried using t.Apply(), but it doesn't change anything at all. Everything looks the same.
Oops ... just saw it: your index calculation is wrong [i*j]. If j == 0 in the first loop you're setting colors[0] 50x times ( 0*0, 1*0, 2*0, ... ). It's colors[j*50 + i]
Your answer
Follow this Question
Related Questions
Why my Image.sprite keeps saying null ?? Help! 0 Answers
problem with arrays and image replacment 0 Answers
Change Sprite according to user choice 0 Answers
Can you pass a RawImage to an IEnumerator in another script? 0 Answers
Save a Image's state 1 Answer