- Home /
Dynamically set the sprite of a button in loop
Hi, I am working on Unity 4.7 project and have 15 UI buttons on my scene (named Button1, Button2, ...) and want to dynamically set the sprites or textures to it. I did it on next way:
public Button[] buttonsFlags = new Button[15];
...
public class TextureLoader
{
public Sprite[] textures;
public void LoadTextures(string pgNumber)
{
string path = "Flags/page" + pgNumber;
textures = Resources.LoadAll<Sprite> (path);
}
}
public void FillTheFlagsPage(string pgNumber)
{
textureLoader.LoadTextures(pgNumber);
for (int i = 1; i <= textureLoader.textures.Length; i++)
{
string btnName = "Button" + i.ToString ();
buttonsFlags[i] = GameObject.Find (btnName).GetComponent<Button>();
//buttonsFlags[i].GetComponent<Renderer>().material.mainTexture = textureLoader.textures[i];
buttonsFlags[i].image.sprite = textureLoader.textures[i];
}
}
But it seems something is wrong. I get NullReferenceException: Object reference not set to an instance of an object on line buttonsFlags[i] = GameObject.Find (btnName).GetComponent(); Please help me to find right way to do this.
Your answer
Follow this Question
Related Questions
Assigning a function with a parameter to buttons in for loop with a temp variable 1 Answer
Gathering GameObjects and then creating a button for each GameObject?? 2 Answers
How to play a Video IN a UI Button / as a Button? 0 Answers
Problems with render priority in UI Canvas 2 Answers
Issue with spawning buttons and assigning listeners 1 Answer