using UnityEngine; namespace Gley.TrafficSystem { /// /// Add this component on the Vehicle prefab if you need engine sound for your vehicle /// [RequireComponent(typeof(AudioSource))] public class EngineSoundComponent : MonoBehaviour { [Tooltip("Pitch used when vehicle is stationary")] public float minPitch = 0.6f; [Tooltip("Pitch used when vehicle is at max speed")] public float maxPitch = 1; [Tooltip("Volume used when vehicle is stationary")] public float minVolume = 0.5f; [Tooltip("Volume used when vehicle is at max speed")] public float maxVolume = 1; private AudioSource _audioSource; /// /// Initialize the sound component if required /// public void Initialize() { _audioSource = GetComponent(); _audioSource.loop = true; } /// /// Play sound is vehicle is enabled /// /// public void Play(float masterVolume) { _audioSource.volume = masterVolume; _audioSource.Play(); } /// /// Stop volume when vehicle is disabled /// public void Stop() { _audioSource.Stop(); } /// /// Update engine sound based on speed /// /// current vehicle speed /// max vehicle speed /// master volume public void UpdateEngineSound(float velocity, float maxVelocity, float masterVolume) { float percent = velocity / maxVelocity; _audioSource.volume = (minVolume + (maxVolume - minVolume) * percent) * masterVolume; float pitch = minPitch + (maxPitch - minPitch) * percent; _audioSource.pitch = pitch; } } }