- Home /
Play sound only once
I want to play sound only once, after the player jumps on it. So if the character goes back and jumps on it again, it wont play.
This is my script:
public Sprite flagClosed;
public Sprite flagOpen;
private SpriteRenderer theSpriteRenderer;
public bool checkpointActive;
public AudioSource checkSound;
// Use this for initialization
void Start () {
theSpriteRenderer = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Player")
{
checkpointActive = true;
this.gameObject.GetComponent<Animator>().SetBool("Has Passed",true);
}
}
Hope somebody can help
Comment
Best Answer
Answer by Besi2019 · Apr 14, 2018 at 11:15 PM
So at the end is like this?
void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Player")
{
checkpointActive = true;
this.gameObject.GetComponent<Animator>().SetBool("Has Passed",true);
checkSound.Play();
if (!soundHasPlayed)
{
//Play the sound
soundHasPlayed = true;
}
}
}
checkSound.Play() should go only happen when soundHasPlayed is false, so, like this:
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
checkpointActive = true;
this.gameObject.GetComponent<Animator>().SetBool("Has Passed", true);
if (!soundHasPlayed)
{
checkSound.Play();
soundHasPlayed = true;
}
}
}
Answer by James9270_ · Apr 14, 2018 at 11:02 PM
Create a bool to determine whether the sound has played, check if the bool is false before playing the sound, and set it to true after having played the sound. Something like this:
private bool soundHasPlayed = false;
...
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
...
if (!soundHasPlayed)
{
//Play the sound
soundHasPlayed = true;
}
}
}