[Help] How to prevent sound repeating (in this script)

The premise of the below script is; the object it’s attached to should move towards the player when their back is turned, and not move when it is being looked at. While it is moving however, it should make a noise which is declared by the movingSound variable.

Since this is all done via the update function, I’ve created a Boolean for when the sound should/shouldn’t be played; to stop the sound from playing every frame. Despite my efforts, it still seems to play over each-other; the sound echoing over itself in-game, and I can not for the life of me figure out why. Any help would be greatly appreciated.

var target : Transform; //the enemy's target
var moveSpeed = 3; //move speed
var stopSpeed = 0;
var rotationSpeed = 3; //speed of turning
 
var myTransform : Transform; //current transform data of this enemy

var movingSound : AudioClip;
public var soundplaying : boolean;
 
function Awake()
{
    myTransform = transform; //cache transform data for easy access/preformance
}
 
function Start()
{
     target = GameObject.FindWithTag("Player").transform; //target the player
     soundplaying = false; //Stop the sound from playing on start.
 
}
 
function Update () {
 
    var Speed = moveSpeed;
 
    if (renderer.isVisible)
    {
    myTransform.position += myTransform.forward * stopSpeed * Time.deltaTime;
    rigidbody.isKinematic = true;
    soundplaying = false;
    }
 
    if(!renderer.isVisible)
    {
    rigidbody.isKinematic = false;
    myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
    soundplaying = true;
    
        //rotate to look at the player
    myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
    Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
    }
    
    if (soundplaying == true) {
    audio.PlayOneShot(movingSound, 1);
    }
    
    if (soundplaying == false) {
    audio.Stop();
    }
 
}

Just check if the audio is already playing or not.

if(!audio.isPlaying)
    audio.Play();

Click here for more information on AudioSource.IsPlaying

Having a sound play, then not be able to play again for 2 seconds – that’s that same math as being able to shoot a bullet only once every two seconds. Should be able to look up limiting bullets/jumps/… and copy it.

Just in case, the Unity Way of making a delay looks like this. It goes inside all the other “do I want to play the sound” logic:

float nextSoundTime=0; // can't play sounds if before this time

// can't play if last one not finished:
if(Time.time>=nextSoundTime) {
  audio.PlayOneShot(someSound);
  // write down when we will be finished:
  nextSoundTime = Time.time + someSound.length;

}

How about this?

 if (soundplaying == true)
 {
    audio.PlayOneShot(movingSound, 1);
    soundplaying = false;
 }

Then make the stop routine an else or leave it out?