I am having trouble with an Audio script that doesn't reset

So my script is behaving irrationally. I basically have a delayed timer that triggers an audio file to alert the player they are suffocating. There is a collision element with oxygen cans (Tagged as “ReplenishObject”)and every time the player collides with it, the audio should restart.

Here is the problem:

The audio doesn’t play sometimes when it is loaded into the scene or gameObject and when I changed it to use the “Invoke” method, it doesn’t reset as intended. Here is the code below:

Note: There is a empty update at the bottom because this is my 6th iteration of this script and I was gonna try to move the .play() in there for cleaner code but yeah. It doesn’t do as it is intended.

The result I am trying to get:
Timer goes down in 15 seconds and after 15 seconds, trigger the sound. If player touches “ReplenishObject” reset the timer.

Thank you, fellow White hats.

using UnityEngine;
using System.Collections;

[RequireComponent (typeof(AudioSource))]

public class OxygenAlarm : MonoBehaviour
{ //Created a script based on TrueOxygenMeter.
// The script triggers a sound after 10 sounds

private AudioSource myAudioSource;

void Start()
{
myAudioSource = GetComponent(); //Find AudioSource to attach this script

}
void OnCollisionEnter(Collision collider)
{
if(collider.gameObject.CompareTag(“ReplenishObject”)){ //When the player touches a Oxy can. It stops the file

myAudioSource.Stop();

} else

{
Invoke(“OxyAlarm”, 15.0f);

}
}

void OxyAlarm()
{

myAudioSource.Play();
}

void update()
{

}

}

Hi sir!

I think I’d try to work with timer values in the update loop to be able to keep an eye on what’s going on. This is my (non-tested) take on your idea:

[RequireComponent(typeof(AudioSource))]
public class OxygenAlarm : MonoBehaviour
{
    public float alarmTimeThreshold;
    public AudioClip alarmClip;

    private float timerStart = float.MaxValue;
    private AudioSource audioSource;

    void Start()
    {
        audioSource = GetComponent<AudioSource>();
        audioSource.clip = alarmClip;
    }

    void Update()
    {
        if (Time.time - timerStart > alarmTimeThreshold && !audioSource.isPlaying)
        {
            audioSource.Play();
        }
    }

    public void StartOxygenTimer()
    {
        timerStart = Time.time;
    }

    public void StopOxygenTimer()
    {
        timerStart = float.MaxValue;
        audioSource.Stop();
    }
}