This is an older post, but as I still am to find a proper answer to the question. I’ll give my two cents.
The way I did this for my music theory game, was to swap out the piano key button’s source image to the one of my selected piano key through a script attached to the event trigger attached to my button. Once the key has been pressed again (to deselect), or the answer has been submitted, the method swap right back to the regular sprite.
This logic is very game specific, but you can customise it to do whatever you need it to do.
/// <summary>
/// Responsible for switching the sprite of the piano key and selecting the key.
/// </summary>
/// <param name="key">Reference to the button of the piano key</param>
/// <param name="isUserInput">To check if the input is from the user or the GameCtrl</param>
public void SelectKey(Button key, bool isUserInput)
{
bool isSelected = key.GetComponent<NoteValue>().isSelected;
bool isNaturalNote = key.GetComponent<NoteValue>().isNaturalNote;
// check if the key has already been selected
if (!isSelected)
{
// check if it's a natural note
if (isNaturalNote)
{
// swap sprite for white key selected
key.GetComponent<Image>().sprite = ui.whiteKeySelected;
// change is selected to be true
key.GetComponent<NoteValue>().isSelected = true;
}
else
{
// swap sprite for black key selected
key.GetComponent<Image>().sprite = ui.blackKeySelected;
// change is selected to be true
key.GetComponent<NoteValue>().isSelected = true;
}
}
else
{
if (isNaturalNote)
{
// swap sprite for white key
key.GetComponent<Image>().sprite = ui.whiteKey;
key.GetComponent<NoteValue>().isSelected = false;
}
else
{
// swap sprite for black key
key.GetComponent<Image>().sprite = ui.blackKey;
key.GetComponent<NoteValue>().isSelected = false;
}
}
if (isUserInput)
{
// register key as selected or unselected, for the answer checker
}
}
NoteValue is an attached script with note values (as the name indicates), such as note value, Audioclip for when key is pressed and helper booleans as used above.
The method can’t take a Button as a parameter from the event trigger, so I created a helper method to get the Button component and pass in the isUserInput as true, instead of sending the button as gameObject from the GameCtrl and then getting the Button component from both objects inside the method. But again, very specific to my use case.
I have taken a screen shot of the important stuff in the inspector.
I don’t know if this is a good solution or not, but it gets the job done (at least for my needs), doesn’t compromise with want I wanted of functions and works flawlessly - both when the button is pressed by user input and called through the game manager. It also allows for multiple selections - very useful for later in the game when notes make up chords and scales and so on.
Hope this is somewhat helpful to anyone stumbling upon this question.
[148677-skærmbillede-2019-11-13-kl-211821.png|148677]