Syntax error when turning off audio

public class endcontrol : MonoBehaviour {
   

    // Use this for initialization
    void Start () {
       
    }
   
    // Update is called once per frame
    void Update () {
       
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.name == "endcheck" && Notecontrol.Life > 1)
        {
            Destroy(gameObject);
            AudioSource.Stop();
        }
    }
}

When i wrote “AudioSource.Stop();”, It gave me a syntax error saying “an object reference is required for the non-static field, or property “AudioSource.Stop();””.

I’m fairly new to c# so I can’t figure out why this error exists. Any help is appreciated.

You need an instance of the AudioSource class since Stop() is not a static member.
You have to set up an instance variable like this:

AudioSource _audioSource;

Then you can call _audioSource.Stop();

public class endcontrol : MonoBehaviour {
  
    AudioSource _audioSource;

    // Use this for initialization
    void Start () {
      
    }
  
    // Update is called once per frame
    void Update () {
      
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.name == "endcheck" && Notecontrol.Life > 1)
        {
            Destroy(gameObject);
            _audioSource.Stop();
        }
    }
}
1 Like

Now, instead of giving me a syntax error, It says the following in the console

“Object reference not set to the existence of an object”

this is confusing because I had already set the code to an object

any help?

You also have to assign the variable to an existing game object.
Maybe something like _audioSource = gameObject.GetcComponent(); ?

public class endcontrol : MonoBehaviour {

    AudioSource _audioSource;

    // Use this for initialization
    void Start () {

         // This will assign the AudioSource object to the variable.. This depends on the
         // location of the GameObject that has the AudioSource component in the scene.
         // You may need to do a search for the GameObject that has the component if you
         // put it on a different GameObject than where the endcontrol script is located.
         // If the AudioSource component is located on the same object, you can find it..
         // like this:
         _audioSource = gameObject.GetComponent<AudioSource>();
 
    }
    // Update is called once per frame
    void Update () {
 
    }
    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.name == "endcheck" && Notecontrol.Life > 1)
        {
            Destroy(gameObject);
            _audioSource.Stop();
        }
    }
}