How can I play audio while a non player controlled object is moving and stops playing when object stands still?

I am new at scripting and c#.

In my scene there are some physics based objects that slide down slopes, which get steepened via scripts. These objects are boxes that grind down the slope and spheres that roll down the slopes. They make different sounds, so I need a solution that can play a sound (looping) until the object stops moving or is falling off of an edge thus not rolling any more.

I am asking this here as I have no idea on how to start this. I can not use player input to determine when the sound plays.

Thank you for any insight.

You’ll presumably be dealing with an object that has an attached Collider, Rigidbody, and AudioSource. Off the top of my head, here’s how I would try to implement what you’ve described:

private float thresholdSpeed = 5.5f; // Adjust this value as desired

// OnCollisionStay is called once per frame for every collider that is touching another collider.
void OnCollisionStay(Collision collisionInfo){
	// Check if the speed of the object exceeds the threshold
	if (rigidbody.velocity.magnitude > thresholdSpeed){
		// If the AudioSource isn't playing, start it
		if (!audio.isPlaying){
			audio.Play(); // Probably best to enable looping of the audio clip in the AudioSource settings or via audio.loop
	else{ // Object is touching something, but isn't moving fast enough
		// If the AudioSource is playing, stop it
		if (audio.isPlaying){
			audio.Pause(); // Pausing is probably better than stopping for looping sounds since it avoids always playing the loop from the start

I haven’t tested this, but I think this general idea should work. You’d also need a status variable to indicate when the object isn’t touching anything (to stop the sound if the object stops touching any other objects while still travelling at a speed above the threshold), but that could be handled using a boolean set by OnCollisionStay(). Alternatively, using OnCollisionExit() might work (just place audio.Pause() inside).

At any rate, I hope that helps!