Flickering sound to go with flickering light

Hi. I’ve got a flickering light set up, and I’ve been wondering if there’s a way to have a sound attached to it flicker along with the light. I know I could just make the sound flicker “hardcoded” in the actual audio, but I kinda want the flickering to be accurate. Here’s my code for the light:

using UnityEngine;
using System.Collections;

public class flick : MonoBehaviour {
	
	private int randomizer = 0;
	private float brightness;
	public int freq = 20;
	public int lowfreq = 1;
	public AudioClip lightSound;
	private AudioSource lightAudio;
	private Light lightObject;
	public bool active;

	void Awake ()
	{
		lightAudio = GetComponent<AudioSource> ();
		lightAudio.clip = lightSound;
		lightObject = GetComponent<Light> ();
		brightness = lightObject.intensity;
	}

	public void OnActive()
	{
		active = !active;
		lightObject.enabled = !lightObject.enabled;
		if (active) {
			lightAudio.Play ();
		} else
			lightAudio.Stop ();
	}

	void Update() {
		if (active) {
			if (randomizer <= lowfreq) {
				lightObject.intensity = 0;
			} else
				lightObject.intensity = brightness;
			randomizer = Random.Range (0, freq);
		}
	}
}

So when the light is active, I have it so a looping fluorescent light sound plays. I’ve tried adding something like “lightAudio.volume = 0;” and “lightAudio.volume = 1;” to the update section, but it doesn’t appear to work. Unless it’s flickering too fast and my ears just aren’t picking it up.

I’ve also tried a .Pause and .Play, on lightAudio but, while it works, it is not synced to the light flicker.

Is it even worth attempting to fix, as it’s just a minor detail?

My first thought would be to try using a Coroutine.

So, instead of your update function try this (untested):

    bool lightOn;

	void Awake ()
	{
		lightAudio = GetComponent<AudioSource> ();
		lightAudio.clip = lightSound;
		lightObject = GetComponent<Light> ();
        brightness = lightObject.intensity;
		lightOn = true;
	}
	
	public void OnActive()
	{
        active = !active;
		lightObject.enabled = !lightObject.enabled;
		if (active) {
			StartCoroutine(FlickyLight());
		}
	}
	IEnumerator FlickyLight(){
		while (OnActive) {
			int randomTime = MathF.randomRange (1, 10);
			if(lightOn){
				lightObject.intensity = 0;
				lightAudio.Stop ();
				lightOn = false;
				yield return new WaitForSeconds(randomTime*0.1F);
			} else {
				lightObject.intensity = brightness;
				lightAudio.play ();
				lightOn = true;
				yield return new WaitForSeconds(randomTime*0.1F);
			}
		}
	}

This way if you choose to set the light as not active then you will be able to void the whole FlcikyLight() part. The coroutine should allow the pause to be long enough for you to be able to see a difference.