- Home /
PlaySound Once After Activated
So I have a door that Activates once the Player Enters Its Collider. I only need the sound to play once but I am terrible with Scripting. After the door is already opened the Player can collide with it and it will play the sound again, as i intend it to only play once. Ive Tried Changing _audioSource.Play(); to _audioSource.PlayOneShot(); but it doesnt seem to work. I have also watched numerous tutorials and looked at other peoples questions but they all seem to be extremely specific and dont match with my problem.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class DoorScript : MonoBehaviour {
private Animator _animator;
private AudioSource _audioSource;
private void Awake()
{
_animator = GetComponent<Animator>();
_audioSource = GetComponent<AudioSource>();
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
_animator.SetBool("open", true);
_audioSource.Play();
}
}
}
What is it not doing? Is the sound not playing at all? Is the animator bool setting? Try debugging.
Sorry, i forgot to mention. After the door is opened the player can collide with the door again and the sound plays again.
Answer by Andromedog · Jun 27, 2019 at 01:37 AM
So two things:
First, make sure that the audiosource isn't called on multiple times. This could happen for multiple reasons due to multiple colliders on the player, or the sound being called in other scripts.
Otherwise, the audiosource could be on 'loop'. If 'loop' is off the sound should only play once.
Second, is a question. Is the door animated? If so, there may be a easier way of timing your sound and having it only play once.
What you can do then is use an Animation_Event to call your sound. When you look at your animation in the "Animation Tab", it will be the symbol that kind of looks like a banner. Place that in your animation and have a script that calls for the sound to play. The sound will only play when it reaches that point in the animation.
If you want more details on Animation_Events, check out this video:
Just got it to work! thanks! I didnt know that you could activate sounds through animations :)
Your answer
Follow this Question
Related Questions
How to play multiple audio files from one script 1 Answer
Unity plays only a few gameobject's sound 2 Answers
Sound play in spot of particle collision 1 Answer
AudioClip calculates length wrong 1 Answer
Roll A Ball Sound 1 Answer