To combine the two scripts, we can merge the functionality into a single script. We'll incorporate the AudioSpectrum class's functionality into the ParticleController class. This way, we only have one script to attach to the GameObject, and it will handle both the audio spectrum analysis and the particle system response.
Here's the combined script:
using UnityEngine;
using UnityEngine.Audio;
[RequireComponent(typeof(AudioSource))] // Ensure there's an AudioSource on the GameObject
public class ParticleSystemAudioReactive : MonoBehaviour
{
public AudioMixer mixer;
public ParticleSystem particleSystem;
private float[] _samples = new float[512]; // Size can be adjusted based on your needs
private ParticleSystem.MainModule mainModule;
private AudioSource _audioSource;
void Start()
{
// Initialize the AudioSource and MainModule references
_audioSource = GetComponent<AudioSource>();
mainModule = particleSystem.main;
}
void Update()
{
// Get the data from the Audio Mixer
mixer.SetFloat("MusicVol", Mathf.Log10(_audioSource.volume) * 20);
_audioSource.GetSpectrumData(_samples, 0, FFTWindow.Blackman);
// Use the spectrum data to drive the particle system
float bandValue = GetBandValue(1); // Use the appropriate band
// Adjust particle size
mainModule.startSize = Mathf.Lerp(mainModule.startSize.constant, bandValue * 2, Time.deltaTime);
// Adjust color
mainModule.startColor = Color.Lerp(Color.blue, Color.red, bandValue);
// Adjust emission rate
var emission = particleSystem.emission;
emission.rateOverTime = bandValue * 100;
// Adjust other properties as needed
}
// This function can be used to get the specific frequency band value
public float GetBandValue(int band)
{
if (band >= 0 && band < _samples.Length)
{
return _samples[band];
}
return 0f;
}
}
You can attach this script onto the GameObject with the Particle System and assign the required references (the AudioMixer and the ParticleSystem) in the Inspector. Make sure the GameObject also has an AudioSource component, as the script now expects it to be present (due to the [RequireComponent(typeof(AudioSource))] attribute).
Please note, the GetBandValue method and the _samples array are now part of the ParticleSystemAudioReactive class, so they are not publicly exposed. If you need to access the audio spectrum data from other scripts, you may consider making GetBandValue public or exposing the necessary data through public properties or methods.