0
votes

Recently I started making a prototype game in Unity. But I have some problems with the audio. I use audio.Play(); but nothing happens. Here is the code:

The initialization:

public AudioClip jumpland;
AudioSource audio;
void Start() { audio = gameObject.GetComponent<AudioSource> (); }

Playing the Sound:

void OnTriggerEnter2D(Collider2D col) { 
    if (down.GetComponent<BoxCollider2D> ().gameObject.tag == "block") {

        audio.clip = jumpland;
        audio.Play ();
    }
}

The audio clip is assigned but it wont play.

1
generally you NEVER NEED "AudioClip" in your code for any reason, ever. Just have (say) five game objects which are an AudioSource - have them all set-up with a sound effect (or whatever) already dragged on to them, with the volume set and so on. Just have five "public AudioSource sfx1;" variables in your code. Simply, play whichever one you want (sfx1.Play()). "It's that simple". - Fattie

1 Answers

1
votes

Ok so I had to play it from the "down" game-object script. And I put it in a method so I made this method:

PlaySound(AudioClip clip) {

audio.clip = clip;
audio.Play();
}

and I just call this by using:

PlaySound(jumpland);