Smooth damp the lowpass frequency in coroutine: value only changing in 1 frame

Hi,

Sorry - I really should have worked out how to use this correctly by now, but I just can’t work out what I’ve set up wrong.

I want to fade the lowpass cutoff frequency from 300 up to 22000 over a period of several seconds.
However - the value is only changing once. Does anyone know what I’ve set up wrong?

using UnityEngine;
using System.Collections;

public class SetScreensInactive : MonoBehaviour {

	public GameObject aboutScreen;
	public GameObject creditsScreen;
	public GameObject buttonAbout;
	public GameObject buttonCredits;
	public AudioSource mainAmbient;
	AudioLowPassFilter filterAudio;
	public GameObject titleSound;

	public float frequencyLerped;
	float audioChange;
	float min = 300;
	float max = 22000;
	float t = 0;
	float duration = 1;

	void Update () 
	{
		int nbTouches = Input.touchCount;
		
		if(nbTouches > 0)
		{
			for (int i = 0; i < nbTouches; i++)
			{
				Touch touch = Input.GetTouch(i);
				
				if(touch.phase == TouchPhase.Began)
				{
					if(touch.tapCount >= 1)
					{
						aboutScreen.SetActive(false);
						creditsScreen.SetActive (false);
						buttonAbout.SetActive(true);
						buttonCredits.SetActive (true);

						StartCoroutine(FadeLowPass());

					//	filterAudio.cutoffFrequency = 300;
					}
				}
			}
		}
	}

	IEnumerator FadeLowPass()
	{
		if (frequencyLerped < 22000)
		{
			filterAudio = titleSound.GetComponent<AudioLowPassFilter>();
			frequencyLerped = Mathf.SmoothDamp (frequencyLerped, 22000, ref audioChange, 2f);
			filterAudio.cutoffFrequency = frequencyLerped;
			print (frequencyLerped);
		}
		yield return null;

	}
}

Best,
Laurien

1 Answer

1

Coroutines are like simple methods, only difference is that they provide delay mechanism. So here when you start the coroutine it executes your if, then it waits one frame at yield statement and exits. what you need is everything wrapped up in a while loop. something like this

IEnumerator FadeLowPass()
     {
       while(true){
         if (frequencyLerped < 22000)
         {
             filterAudio = titleSound.GetComponent<AudioLowPassFilter>();
             frequencyLerped = Mathf.SmoothDamp (frequencyLerped, 22000, ref audioChange, 2f);
             filterAudio.cutoffFrequency = frequencyLerped;
             print (frequencyLerped);
         }
         yield return null;
      }
     }

That's great - I understand now! (finally!) If you convert your comment to an answer I can tick it as answered! Thank you :)