- Home /
Get audio to just play once
Hi, my audio repeats even though I don't have loop checked on the Audio Source.
How can I get my audio to just play once:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class DoorController : MonoBehaviour {
public Animator anim;
public AudioClip VaultOpening;
public bool isOpen;
public List<Pickup.ItemType> requiredItems = new List<Pickup.ItemType>();
void Update()
{
if(isOpen)
{
//if door is open code
anim.enabled = true;
GetComponent<AudioSource> ().clip = VaultOpening;
if (!GetComponent<AudioSource>().isPlaying)
GetComponent<AudioSource>().Play();
}
else
{
//if door is closed code
anim.enabled = false;
}
if (requiredItems.Count == 0) isOpen = true;
}
}
Answer by dan_wipf · Aug 20, 2018 at 08:44 AM
well your audiosource will play imedeiatly after clip is finished again. because you check if the audiosource isnt playing, which is always true when the clip is finished. maybe try it with a bool if it’s a one time thing you could set the bool in the start function to true. and the when the audioclip is finished to false. something like this:
bool sound;
void Start()
{sound =true;}
void Update()
{
if (sound)
{audisource.Play();
if (!audiosource.isPlaying){
sound = false;
}
or this might work as well if you take out the if statement: if (!GetComponent().isPlaying)
So then it should be like this?
public class DoorController : $$anonymous$$onoBehaviour {
public Animator anim;
public AudioClip VaultOpening;
public bool isSoundOn;
public bool isOpen;
public List<Pickup.ItemType> requiredItems = new List<Pickup.ItemType>();
void Start()
{ isSoundOn = true;}
void Update()
{
if(isOpen)
{
//if door is open code
anim.enabled = true;
}
else
{
//if door is closed code
anim.enabled = false;
}
if (isSoundOn)
{
audisource.Play();
if (!audiosource.isPlaying)
{sound = false;}
}
if (requiredItems.Count == 0) isOpen = true;
}
}
yes i guess so, did it solve your problem? Edit: might wamt to change in the update function line If(isSound) this if(isSoundOn && isOpen)
Your answer
Follow this Question
Related Questions
audio.clip.GetData() returns no data. 0 Answers
Unity 5 low audio volume 1 Answer
Playing many audioclips with PlayOneShot causes all sound to cut out. 0 Answers
Truncate audio runtime 0 Answers
Play sound from an array, not random, and only once 3 Answers