How do you make loop sounds exclusive to distance in C#?

In my game, when the enemy gets to a certian distance, audio (for an example, the sound is called “bread”) will be played/looped. When he is farther away (or you move farther away) the audio will stop playing (but will still be true to play when the enemy gets close again to you).
As you progress (let’s say, you collected 3 “bacon strips” [for an example]) the distance needed to play the audio will be longer than when you were at one.

Can someone please give me an example using those listed above (I ask only so I can figure where to put “audio” and where to put “bread”)?

First on the object that gets the distance with the player


public float distSqr=10;
Transform player;
Transform _transform;

void Start(){
   player =GameObject.Find("Player").transform;
   _transform = GetComponent<Transform>();

void Update(){
   float dist = (player.position - _transform.position).sqrMagnitude;
   }else if(audio.isPlaying) audio.Stop();

Now on the player:

int bread=0;
ObjectDistance script;

void Start(){
   script =GameObject.Find("DistanceObject").GetComponent<ObjectDistance>();

void OnTriggerEnter(Collider col){
   if(col.gameObject.tag =="Bread"){
      script.distSqr += 10;
      bread +=1;

Now for explanations, the first script is attached to the object that plays the sound. It checks the distance with the player. I use sqrMagnitude because it is cheaper than Distance which involves sqr root. So consider that all distances are squared, so 10 is actually 3.33333m.

If the dist is smaller than the define distance then we check if the audio is not already playing and if not then we play.
If the dist is greater then the audio is stopped or finally nothing happens.

The player has the second script. First we get a reference to the script of the sound object. Then the bread has a trigger collider and if we enter it then we go to add 10 to the sqrDistance (so 3.33333m more in real) and we increase the amount of bread.

Hopefully it works.