0
\$\begingroup\$
void OnMouseDown ()
{
    foreach (Button thisButton in buttonArray)
    {
        thisButton.GetComponent<SpriteRenderer>().color = Color.black; 
    }

    GetComponent<SpriteRenderer>().color = Color.white;
}

This code results in whichever button I select changing color to white while the rest are black. However, I am not understanding how this works. How does it know to specifically change ONLY the selected button to white while the rest are black. Seems contradictory to me...

\$\endgroup\$
  • \$\begingroup\$ Every time you click a button, it puts every button black (even those that are already black: it 'resets' it to it's default state, which is black), that's done in the foreach loop; then it colours only the one that you want. I'm not sure what else you're looking after. \$\endgroup\$ – Alexandre Vaillancourt Feb 2 at 2:20
  • \$\begingroup\$ I would rather think about removing this code at all. This behaviour already exists natively in Unity. Are you trying to recreate native behaviour? Or is it different in some way due to requirements? The code: foreach button in array make it black, then get the SpriteRenderer on this gameobject and make its color white. \$\endgroup\$ – Candid Moon _Max_ Feb 2 at 11:56
0
\$\begingroup\$

On every MouseDown event call, in the foreach loop, the color of all buttons changes to black, then the button which cause to call MouseDown event,it's color changes to white. Note that thisButton.GetComponent<SpriteRenderer>().color refer to color of each button,but GetComponent<SpriteRenderer>().color refer to clicked button color.

\$\endgroup\$

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.