- Home /
Audio source play stop in Unity5
... I cant get the audio source to play in Unity5. I want to play an audio clip on loop until I tell it to stop. Does anyone know how to make it work? The docs do not make any examples at all. My audio source: var warningToStar : AudioClip;
if (shipToSun == true) {
var warningToStar = GetComponent<AudioSource>.Play();
//audio.Play();
}
else if (shipToSun == false) {
var warningToStar = GetComponent<AudioSource>.Stop();
//audio.Stop();
}
Answer by Snownebula · May 26, 2015 at 12:51 PM
Thanks guys, but I didn't have internet last night and this is what I came up with or anyone who sees this post down the road. Perhaps someone here did it better than me? I will try yours out and see if it works better :D I am not sure witch is best. var othersun : Transform; var closeDistanceSun = 30;
var warningToStar : AudioClip;
var warningTimer : int = 5;
public var shipToSun : boolean = false;
function Start () {
}
function Update () {
closeSunWarn();
}
function closeSunWarn () {
othersun = GameObject.FindWithTag("t6").transform;
if (other) {
var offset = othersun.position - transform.position;
var sqrLen = offset.sqrMagnitude;
// square the distance we compare with
if( sqrLen < closeDistanceSun*closeDistanceSun ) {
//print ("The other transform is close to me!");
shipToSun = true;
}
else if( sqrLen > closeDistanceSun*closeDistanceSun ) {
//print ("The other transform is close to me!");
shipToSun = false;
}
}
}
function CheckActive1 () {
if (shipToSun == true) {
warningTimer -= 1;
if (warningTimer < 1) {
GetComponent.<AudioSource>().PlayOneShot(warningToStar);
warningTimer = 5;
}
}
}
Answer by vk007 · May 26, 2015 at 03:54 AM
The audio source has a loop boolean which you can check to get it to loop.
That should make it loop and your code seems correct, so it should stop and play.
Answer by Potote · May 26, 2015 at 03:57 AM
The answer is really simple
You put your play in a selection sentence insteaf of a loop like for or while:
var warningToStar = GetComponent<AudioSource>();
while (ShipToSun == true){
warningToStar.Play;
}
The problem, is that in a while loop, can execute a lot of time per seconds, y prefer to do a corutine or a invoke method, with the time to loop is the audio clip time:
var warningToStar = GetComponent<AudioSource>();
public void repeat_method(){
if (shipToSun == True){
warningToStar.Play();
invoke("repeat_method",warningToStar.time);
}
}
I hope i can resolve your issue
Your answer
Follow this Question
Related Questions
Looping an AudioClip var... 1 Answer
3D audio source not playing on trigger 0 Answers
Audio/c#/unity Can i control the duration by time ? 1 Answer
Why Won't My Audioclip Loop Seamlessly? 1 Answer
What could make the audio loop? 2 Answers