I'm trying to synchronize a rotating propeller with a engine sound by changing the sound's pitch.
I have a script attached to an airplane's propeller which, after the game starts, causes it to gradually increase rotation speed from slow to maximum.
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spin : MonoBehaviour { public float RotationSpeed = 1; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { transform.Rotate(0, 0, RotationSpeed, Space.Self); if (RotationSpeed < 10) { RotationSpeed += 1f * Time.deltaTime; } } } On an empty gameobject I added an AudioSource and made its AudioClip an .mp3 sound effect of a propeller. To this gameobject I attached this script:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AudioExample : MonoBehaviour { public int startingPitch = 4; public int decreaseAmount = 5; public Spin spin; private AudioSource _audioSource; void Start() { _audioSource = GetComponent<AudioSource>(); _audioSource.pitch = startingPitch; } void Update() { if (_audioSource.pitch > 0) { _audioSource.pitch += Time.deltaTime * startingPitch / spin.RotationSpeed; } } } Screenshot of the propeller object :
and a screenshot of the gameobject with the AudioSource component:
The pitch in the audio source by default starts at value 1 and should be changed between the values of -3 and 3. The rotation speed in the Spin script is in other units.
The behavior I want is: as the propeller starts rotating slowly and increases to max speed, the audio source pitch will automatically change its value in sync with the propeller rotation speed.
However, the script AudioExample as it is now is making the pitch value to well exceed 3, in fact it goes up to 10. The calculation in the AudioExample script is wrong and I'm not sure how to correct it:
_audioSource.pitch += Time.deltaTime * startingPitch / spin.RotationSpeed; 
