- Home /
AudioSource and AudioClip. Stop and play drops an error.
Hello community.
Unity3d console drops me the next error.
MissingComponentException: There is no 'AudioSource' attached to the "FinishLevel" game object, but a script is trying to access it. You probably need to add a AudioSource to the game object "FinishLevel". Or your script needs to check if the component is attached before using it. CambioMusicaBossFinal.OnTriggerEnter2D (UnityEngine.Collider2D colisionador) (at Assets/Scripts/CambioMusicaBossFinal.cs:20)
I've an AudioSource on main camera and there's an audio assigned on the variable "musicaFinal". Here's the script.
using UnityEngine;
using System.Collections;
public class CambioMusicaBossFinal : MonoBehaviour {
private GameObject Jugador_1;
public AudioClip musicaFinal;
void Start ()
{
Jugador_1 = GameObject.FindWithTag("Player");
}
void OnTriggerEnter2D(Collider2D colisionador)
{
if (colisionador.gameObject.tag == "Player")
{
Camera.main.GetComponent<AudioSource>().Stop();
audio.clip = musicaFinal;
audio.Play();
audio.loop = true;
}
}
}
theoretically it has to work because is all assigned, right?
Any help will be appreciated.
Regards.
Answer by Simon-Larsen · Jan 19, 2015 at 04:43 AM
You need to save your reference to the audio source. My guess is this script isn't assigned to the main camera in your scene - since you don't get an error on line 19.
if (colisionador.gameObject.tag == "Player")
{
AudioSource audioSource = Camera.main.GetComponent<AudioSource>();
audioSource.Stop();
audioSource.clip = musicaFinal;
audioSource.Play();
audioSource.loop = true;
}
Solved I've added an AudioSource with the same music that I wanted to play with the AudioClip and it worked.
Thanks for the help!
Here's my code
using UnityEngine;
using System.Collections;
public class Cambio$$anonymous$$usicaBossFinal : $$anonymous$$onoBehaviour {
private GameObject Jugador_1;
private GameObject $$anonymous$$ainCamera;
public AudioClip musicaFinal;
void Start ()
{
Jugador_1 = GameObject.FindWithTag("Player");
$$anonymous$$ainCamera = GameObject.FindWithTag("$$anonymous$$ainCamera");
}
void OnTriggerEnter2D(Collider2D colisionador)
{
if (colisionador.gameObject.tag == "Player")
{
$$anonymous$$ainCamera.GetComponent<AudioSource>().Stop();
if (musicaFinal != null)
{
audio.clip = musicaFinal;
audio.Play();
audio.loop = true;
}
}
}
}