- Home /
Trying to play an AudioSource in a StateMachineBehaviour gives an error message: 'Can not play a disabled audio source'
Hi, when I try to play an audio clip in a StateMachineBehaviour script attached to a specific animation state, I get the error message, "Can not play a disabled audio source". Even turning on the Play on Awake field does not enable any audio. I've checked the checkboxes to see if the audiosource/clip are enabled and they both have checkmarks.
I've also tried using the function call AudioSource.PlayClipAtPoint with the position at the camera, and that seems to play the audio. However the sound is very poor and full of distortion. Is there a way to improve the sound quality of the function?
Code sample is below:
public class PlayAudio : StateMachineBehaviour {
public AudioSource successfulHitSound;
public AudioClip hitSound;
override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
successfulHitSound.enabled = true;
successfulHitSound.Play();
//AudioSource.PlayClipAtPoint (hitSound, Camera.main.transform.position, 1f);
}
}
Any help would be greatly appreciated.
Answer by Darkgaze · Dec 24, 2018 at 05:11 PM
The animatorController is in the asset folder, the audioSource lives in a scene. That's why you can't assign an AudioSource to a State Machine Behaviour.
You can gather the AudioSource using the Animator variable in the OnStateEnter parameters.
animator.GetComponent<AudioSource>();
then you can check if it is null, asign a clip to it and play the sound the same way you did it.