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”)?
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.