Hey there, I’ve just seen too many posts on this topic that have been all about very specific situations so I’d like to ask this generally for myself and anyone else out there. Can anyone help me figure out a way to make the Ball in my Roll-A-Ball project have a rolling sound when it moves? Thanks in advance!
I actually just implemented something similar so I’ll give you the rundown on how I did that.
First of all, you’ll want to choose a sound for the ball to make when it rolls. You will want to have a sound that can loop seamlessly. This may require a bit of editing of whatever sound file you choose.
Once your sound file is ready, import it into Unity and add an AudioSource to the ball. Drag the sound into the AudioClip slot in the inspector and check Loop. Make sure to uncheck Play On Awake.
The ball needs to have a Rigidbody attached.
Presumably you will only hear the rolling sound when the ball is touching the ground and moving. Thus you will only want to play the sound when there is a collision detected between the Collider of the ball and the Collider of the ground and when the ball’s speed is over a certain threshold. To do that I tagged the ground “Ground” and used the following script (attached to the ball):
#pragma strict
private var speed : float;
private var rigidBody : Rigidbody;
private var ballSoundSource : AudioSource;
function Start()
{
rigidBody = GetComponent.<Rigidbody>();
ballSoundSource = GetComponent.<AudioSource>();
}
function FixedUpdate()
{
speed = rigidBody.velocity.magnitude;
}
function OnCollisionStay(collision : Collision)
{
if (ballSoundSource.isPlaying == false && speed >= 0.1f && collision.gameObject.tag == "Ground")
{
ballSoundSource.Play();
}
else if (ballSoundSource.isPlaying == true && speed < 0.1f && collision.gameObject.tag == "Ground")
{
ballSoundSource.Pause();
}
}
function OnCollisionExit(collision : Collision)
{
if (ballSoundSource.isPlaying == true && collision.gameObject.tag == "Ground")
{
ballSoundSource.Pause();
}
}
Hope this helps!
You can try use somthing like this:
float nominalSpeed = 1f;
AudioSource aSource;
Rigidbody rBody;
void MoveSound()
{
aSource.pitch = rBody.velocity.magnitude / nominalSpeed;
}
hi thank you for your work, but i’m lost because i’m on unity 5 and i got many parse error so can you update your code please.,hi thank you for your work, but can you update your code to the version 5 of unity please. because i’m lost.
Please update the code having similar problem
I would suspect that you are getting errors because you are trying to shove this into a C# script? This is a guess, as I don’t know what your error actually is. The above code is in UnityScript and the filename should end in .js not .cs. For most current implementations of Unity, you should translate this into C#.