How do I make this script play a sound effect every time the score increases by 1?

Hello! I’m a beginner in Unity and I was following the flappy bird guide on Unity’s youtube channel.

I learned a lot! Especially how to make sprites/animations/prefabs, these concepts are awesome.

I also searched on the internet and learnt how to add sound inside an animation which is really cool.

However, I can’t figure out (yes I googled this a lot over the last 4 days) how to make the score script play a sound every time the score counts.

I know I need to add some function after this bit scoreText.text = "Score: " + score.ToString();

I just don’t know how to do it and every example I tried didn’t seem to work.

Any help would be very appreciated!

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class GameControl : MonoBehaviour {
   
    public static GameControl instance;         //A reference to our game control script so we can access it statically.
    public Text scoreText;                      //A reference to the UI text component that displays the player's score.
    public GameObject gameOvertext;             //A reference to the object that displays the text which appears when the player dies.

    private int score = 0;                      //The player's score.
    public bool gameOver = false;               //Is the game over?
    public float scrollSpeed = -1.5f;


    void Awake()
    {
        //If we don't currently have a game control...
        if (instance == null)
            //...set this one to be it...
            instance = this;
        //...otherwise...
        else if(instance != this)
            //...destroy this one because it is a duplicate.
            Destroy (gameObject);
    }

    void Update()
    {
        //If the game is over and the player has pressed some input...
        if (gameOver && Input.GetMouseButtonDown(0))
        {
            //...reload the current scene.
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        }
    }

    public void FreelancerScored()
    {
        //The bird can't score if the game is over.
        if (gameOver)  
            return;
        //If the game is not over, increase the score...
        score++;
        //...and adjust the score text.
        scoreText.text = "Score: " + score.ToString();       
    }

    public void FreelancerDied()
    {
        //Activate the game over text.
        gameOvertext.SetActive (true);
        //Set the game to be over.
        gameOver = true;
    }
}

You need to add an AudioSource to the gameobject and link your audio clip with it, then in FreelancerScored you’d do something like:

GetComponent<AudioSource>().Play();
1 Like

Thank you very much! I understand how it works now. My mistake was that I was trying to add the audio source to the text gameobject instead of the controller.

I can finally compile this now! Thank you again!