- Home /
Changing texture of pressed button in array
Hi, I have an array of buttons being created and I want to make it so when I click on a button the texture of the button changes. The code I have changes the texture of all the buttons when I click any of the buttons.
Is there a way to code it so that if I click a button then the texture of that buttons changes from texA to texB and the rest of the buttons stay as texA?
public Texture texA;
public Texture texB;
static Vector2[] loc = new Vector2[25];
bool visited = false;
void Start () {
int i = 0;
while (i < loc.Length){
loc [i] = new Vector2 (Random.Range (Screen.width * 0.1f, Screen.width * 0.9f), Random.Range(Screen.height * 0.1f, Screen.height * 0.9f));
i = i + 1;
}
}
void OnGUI(){
for (int i = 0; i < loc.Length; i++) {
if (GUI.Button (new Rect (loc [i].x, loc [i].y, Screen.width * 0.025f, Screen.height * 0.05f), visited ? texA:texB, "")) {
visited = !visited;
}
}
}
Answer by HarshadK · Mar 07, 2017 at 06:31 AM
Because of having your visited variable as a common variable between all the buttons clicking any button will set it to true and it will be true for all the buttons. You need to store the visited state for each of these buttons separately.
You need to use an array to store the state of each button separately. Something like:
bool[] visited = new bool [ loc.length ];
and your button code becomes:
if (GUI.Button (new Rect (loc [i].x, loc [i].y, Screen.width * 0.025f, Screen.height * 0.05f), visited[i] ? texA:texB, "")) {
visited[i] = !visited[i];
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Array of buttons not displaying in game 1 Answer
Generate Buttons from Array 1 Answer
Simple C# array for changing textures 1 Answer
Adding a texture to array textures?! 1 Answer