Audio Trigger 2D in C#?

Hi there, I’m new to Unity and have been trying to write a few simple codes for a 2D platformer to trigger audio, making the audio play or stop when entering or exiting the colliders that they’re assigned to. I’ve tried looking at other answers and tutorials but I just can’t seem to get it right. Any feedback or help would be greatly appreciated, thanks.

Here’s what I’ve got so far to play music once the player comes into contact with the collider (player is named ‘hero’):

using UnityEngine;
using System.Collections;

public class AudioStop : MonoBehaviour {

	// Use this for initialization
	void Start () {
	
		void OnTriggerEnter2D (2DCollider other) 
		{
			if(other.gameObject.tag == "hero")
			{
				audio.Play(MainTheme);
			}

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

And how would I go about writing something to stop the music once entering a collider?

edit: i just realized this was posted in 2016 but somebody bumped it lol


do you want the audio to shut off when the player is inside the collider? or vice versa?

using UnityEngine;

public class AudioExample: MonoBehaviour {
 
public  AudioSource mainTheme;

bool playAudio;

bool stopAudio ;

void Start()
{   
    audio =  GetComponent<AudioSource>();     
    playAudio =  false;
}
void OnTriggerEnter2D (2DCollider other) 
     {
         if(other.gameObject.tag == "hero")
          { 
               playAudio =  true;
               stopAudio =  true;
          }
     }
void OnTriggerExit2D (2DCollider other) 
     {
         if(other.gameObject.tag == "hero")
          { 
               playAudio =  false;
               stopAudio =  true;
          }
     }
void Update()
{

    if (playAudio== true && stopAudio == true)
    {
        mainTheme.Play();  
        stopAudio = false;
    }

    if (playAudio== false && stopAudio == true)
    {

        mainTheme.Stop();
        stopAudio = false;
    }
}