Conditional Logic Trouble - Matching Input to Audio via Scripts and Prefabs

Hi All,

I am just starting out with Unity via an internship which doesn’t have anyone more skilled/senior that I can ask, I appreciate any feedback!

I built a piano keyboard wth buttons and need to validate the piano key (button) clicked by the user matches the note they’re supposed to play and if they match add a point to the score. However everything is in prefabs (built by prior interns), is there an easy way to do this?

I tried creating condtional if logic to match the audio sources since they’re accessing the same audio file but that isn’t working. I can’t seem to access the audio files in the prefabs and I can only drop one onto the inspector with the script audio source …no clue why I can’t drop the other one in.

Is there a better/easier way to go about doing this other than comparing the audio files? If not, any tips on how to get this to function?

Here is the code I have ATM if it’s helpful:

public class ScoreboardScript : MonoBehaviour
{
    public ScoreboardScript instance;
    [SerializeField] private AudioSource noteSound;
    [SerializeField] private AudioSource notePlay;

    public int scoreNumber;
    public Text scoreText;
    public int scoreValue = 1;

    public bool noteMatch;
    
    private void Awake()
    {
        instance = this;
    }

    public void Start()
    {
        scoreNumber = 0;
        scoreText.text = "Score: " + scoreNumber.ToString();
        noteMatch = false;
        notePlay = GetComponent<AudioSource>();
    }

    public void addScore()
    {
        
        if (notePlay = noteSound)
        {
            noteMatch = true;
            scoreValue = scoreNumber++;
            
            scoreNumber = scoreNumber + scoreValue;
            scoreText.text = "Score: " + scoreNumber.ToString();
        }
        else
        {
            scoreText.text = "Score: " + scoreNumber.ToString();
        }

    }

}

Hi,

The first thing I noticed was your if statement in the addScore() method was setting the notePlay = noteSound when it should be comparing them by using notePlay == noteSound. Also, you are comparing the actual audio sources and not the audio clip, so here is how I would rewrite it:

    public void addScore()
    {
        
        if (notePlay.clip == noteSound.clip)
        {
            noteMatch = true;
            scoreValue = scoreNumber++;
            
            scoreNumber = scoreNumber + scoreValue;
            scoreText.text = "Score: " + scoreNumber.ToString();
        }
        else
        {
            scoreText.text = "Score: " + scoreNumber.ToString();
        }

    }

After I did this, I was able to see the score go up every time I tested it. I hope this helps.