Play a sound once but within the Update function

Hello , i have this code :

var sound:AudioClip[];
var DelayToWait : float; 

function Awake () {


}

function Update () {
    var hit : RaycastHit;
    if (Physics.Raycast (transform.position, transform.forward,hit, 10)) {
        if(hit.collider.gameObject.tag=="shock"){
       audio.clip = sound[Random.Range(0,sound.length)];
    audio.Play();  ;
    yield WaitForSeconds(DelayToWait);
            
              } 
              }   
               
 
 }

I’d like to play those sounds and wait 5 or 6 seconds between each raycast hit , but i can’t put a coroutine in the Update function anyone know how to do that ?

Hi there!

As you’ve mentioned you can’t yield inside Update. What you can do is to either invoke or loop a coroutine outside of Update or have a timer inside Update. I notice you have an unnecessary overhead with hit.collider.gameObject.tag as a collider already has the tag as a inherited variable. You also have a weird semicolon on line 14.

InvokeRepeating

function Start () {
    InvokeRepeating("Shock", 0, DelayToWait);
}

function Shock () {
    var hit : RaycastHit;
    if (Physics.Raycast (transform.position, transform.forward, hit, 10)) {
        if(hit.collider.tag=="shock"){
            audio.clip = sound[Random.Range(0,sound.length)];
            audio.Play();
        }
    }
}

Loop a coroutine

    function Start () {
        Shock();
    }
    
    function Shock () {
        var hit : RaycastHit;
        while (true) {
            if (Physics.Raycast (transform.position, transform.forward, hit, 10)) {
                if(hit.collider.tag=="shock"){
                    audio.clip = sound[Random.Range(0,sound.length)];
                   audio.Play();
                }
            }
            yield WaitForSeconds(DelayToWait);
        }
    }

Timer inside Update

    var sound:AudioClip[];
    var DelayToWait : float; 
    private var nextShock : float = .0;

    function Update () {
        if (Time.time >= nextShock) {
            var hit : RaycastHit;
            if (Physics.Raycast (transform.position, transform.forward, hit, 10)) {
                if(hit.collider.tag=="shock"){
                    audio.clip = sound[Random.Range(0,sound.length)];
                    audio.Play();
                }
            }
            nextShock = Time.time+DelayToWait;
        }
    }