Stan
Stan

Reputation: 13

How to change the AudioClip of an AudioSource from script in Unity?

What I'm trying to do is changing the AudioClip to be played from a script on the AudioSource GameObject depending on the text of an button (difficulty of the game) when the it's pressed.

using UnityEngine;
using UnityEngine.UI;

public class AudioEffects : MonoBehaviour
{
    public AudioClip easyMusic;
    public AudioClip hardMusic;

    public AudioSource audioSource;

    [SerializeField]
    private Text difficultyButtonText;

    public void ChangeMusic()
    {
        var difficultyText = difficultyButtonText.text;
        var audioClip = audioSource.clip;
        
        if (difficultyText == "Easy")
        {
            audioClip = easyMusic;
            audioSource.Play();
        }
        else if (difficultyText == "Hard")
        {
            audioClip = hardMusic;
            audioSource.Play();
        }
    }
}

Searched within the Unity Documentation, but nothing useful for the project. Within StackOverFlow found an answer, but there's no better way of doing it?

Upvotes: 1

Views: 6796

Answers (1)

dowhilefor
dowhilefor

Reputation: 11051

You have never actually changed the value in the audioSource component. Just returning clip doesn't give you a reference to the property, it returns the value of clip. In your case you are creating a variable audioClip with the value of whatever audioSource.clip is at that time. From then on you just change the value in your variable, not your AudioSource component.

To solve it: You could either remove the audioClip variable all together and just assign audioSource.clip directly or set audioSource.clip at the end of your code to audioClip.

Upvotes: 2

Related Questions