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\$
1
  • \$\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 '19 at 11:56
2
\$\begingroup\$

On every MouseDown event call, in the foreach loop, the color of all buttons changes to black, then the button which caused the call to the MouseDown event, its color changes to white.

Note that thisButton.GetComponent<SpriteRenderer>().color refers to the color of each button, but GetComponent<SpriteRenderer>().color refers to clicked button color.

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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