I get the error "MissingComponentException: There is no 'AudioSource' attached .."

I am new to Unity. I am going through 'Unity Game Development Essentials'. I have written code in VB.NET and so I think I would be more comfortable writing scripts in C#. I try converting one of the Javascripts in the book to C#. When I run the script in game mode I get the error "MissingComponentException: There is no 'AudioSource' attached ..". I did post this issue on another thread but as an unregister user. So I thought I would post as a register user. I listed my code below. What am I doing wrong?

using UnityEngine;
using System.Collections;


public class InstructionBtn: MonoBehaviour {

    public Texture2D normalTexture;
    public Texture2D rollOverTexture;
    public AudioClip beep;

    public string levelToLoad;

    // Use this for initialization
    void Start () {


    // Update is called once per frame
    void Update () {

   void OnMouseEnter()  {       
            guiTexture.texture = rollOverTexture;   
            //yield return new WaitForSeconds(.01);

    void OnMouseExit() {
        guiTexture.texture = normalTexture;

    IEnumerator OnMouseUp() {
        yield return new WaitForSeconds(.35f);
    private IEnumerator Yielding(float sec)
        yield return new WaitForSeconds(sec);
    private IEnumerator Yielding1(float sec)
        yield return new WaitForSeconds(sec);

Thanks, Jeff

That actually looks perfect to me - absolutely sure that it's this script that is the problem? If so, have you tried reimporting it?

The RequireComponent attribute up at the top should be adding the audio source automatically

In your code you wrote :


And so that means the object that this code is attached to must have a component of an audio source as well in order for it to work.

It adds the required component when you attach the script to the object, so if you attach it before you wrote the [RequireComponent] bit, it won’t work.

You’d have to reset the script, or remove it and add again.

Or, you can stop using the RequiredComponent attribute and add it when using:

var audioSource = GetComponent<AudioSource>();
if(audioSource == null)
    audioSource == gameObject.AddComponent<AudioSource>();

Please notice this is not the same thing, since it adds when using, if necessary. An alternative is to add it in the Start method, so it would have a similar behaviour as RequiredComponent.