- Home /
play a sound when/while rigidbody velocity is greater than a value
hi guys, I wrote this simple script to play a sound when the enemy, attracted by the player, starts moving. however is not working, no sound is played (I attached an audio source with an audio clip to the gameobject). what did I do wrong?
also I'd like to implement another constant sound while the enemy is moving, after the initial clip is played.
any idea? thanks.
using UnityEngine;
using System.Collections;
public class EnemySound : MonoBehaviour
{
AudioSource AudioSource;
AudioClip hihihi;
public Rigidbody enemy;
void Start()
{
AudioSource.clip = hihihi;
AudioSource.enabled = true;
enemy = GetComponent<Rigidbody>();
}
void FixUpdate()
{
if (enemy.velocity.magnitude >= 0.1 && AudioSource.isPlaying == false)
{
AudioSource.PlayOneShot(hihihi, 0.7F);
}
}
}
you must not call a variable the exact same as the type:
AudioSource AudioSource;
secondly, it's FixedUpdate, not FixUpdate
Answer by abdullahsultan14 · Sep 27, 2018 at 07:26 PM
I believe it is FixedUpdate() rather than FixUpdate() And also change the variable name of AudioSource to something other than the reference name itself
Answer by Bibrosko · Sep 27, 2018 at 10:44 PM
I corrected the code as suggested but the audio clip still does not work
Try adding debug logs in the if statement. Also add debug logs in the update method to keep track of the velocity and do post the updated code if possible
I partially solved the issue doing this. Now the Enemy sound plays but it repeats in a loop ins$$anonymous$$d to play only one time. How can i make it stop after the first execution?
using UnityEngine;
using System.Collections;
public class EnemySound : $$anonymous$$onoBehaviour
{
AudioSource EnemyAudioSource;
public AudioClip hihihi;
public Rigidbody enemy;
void Start()
{
EnemyAudioSource = GetComponent<AudioSource>();
EnemyAudioSource.enabled = true;
enemy = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
if (enemy.velocity.magnitude >= 1 && EnemyAudioSource.isPlaying == false)
{
EnemyAudioSource.PlayOneShot(hihihi, 0.7F);
}
}
}
That is because of the FixedUpdate. As it is usually used to detect changes in a rigid body. And since the rigid body is moving it will keep on detecting this change. You will need to see how you are adjusting the magnitude of the rigid body. As long as the magnitude is greater than 1 the if statement will keep on executing
so there's no other way to play a sound "on moving"?
Your answer
![](https://koobas.hobune.stream/wayback/20220612175401im_/https://answers.unity.com/themes/thub/images/avi.jpg)