Play sound once when door opens, but also when door has been closed again
Hopefully I can explain this. I have an animation of a door opening and closing. When I mouseclick it, the door will open and play the sound of the door opening. But the sound will repeat itself when I click the door again (which is already open). So I put an isPlayed statement in the code. That works.
But the thing is, when I close the door and open it again, the sound of the door opening won't play (because of the isPlayed-statement). How can I make it work that the you can hear the sound once when opening the door and to keep it hearing everytime you close and open the door.
This is my code so far. Thanks for helping me out!
using UnityEngine;
using System.Collections;
public class SoundDeur : MonoBehaviour
{
public Animator anim;
private bool deurOpened = false;
public AudioClip soundFile;
AudioSource mySound;
public bool alreadyPlayed = false;
private bool isPlayed;
void Awake()
{
mySound = GetComponent<AudioSource>();
isPlayed = true;
}
void OnMouseDown()
{
if (!deurOpened)
{
anim.SetTrigger("deuropen");
if (isPlayed)
{
mySound.PlayOneShot(soundFile, 0.8f);
isPlayed = false;
}
}
}
}
Answer by jonahsrocket · Sep 02, 2016 at 07:09 AM
I found my solution so I will share it here. I got rid of the ifPlayed statement and places two soundfiles. Now I stop one sound when the door closes and the other sound plays. I was looking for that statement, which is GetComponent().Stop(); I never knew that it existed. I am a newbie ;)
There are some Dutch words in the code, like Deurdicht, which means doorclosing and deuropen means...you guessed it: dooropen. Who knows someone can use it in a near future.
using UnityEngine;
using System.Collections;
public class SoundDoor : MonoBehaviour
{
public Animator anim;
private bool deurOpened = false;
public AudioClip soundFile;
public AudioClip soundFile2;
AudioSource mySound;
void Awake()
{
mySound = GetComponent<AudioSource>();
}
void OnMouseDown()
{
if (!deurOpened)
{
anim.SetTrigger("deuropen");
{
mySound.PlayOneShot(soundFile, 0.8f);
}
deurOpened = true;
}
else
{
anim.SetTrigger("deurdicht");
{
GetComponent<AudioSource>().Stop();
mySound.PlayOneShot(soundFile2, 0.8f);
}
deurOpened = false;
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612091817im_/https://answers.unity.com/themes/thub/images/avi.jpg)