I want to play an audio clip from the beginning, and make it play forever…
thank you
2 Answers
2attach to an empty game object with an audio source and assign the sound in the inspector
C#:
using UnityEngine;
using System.Collections;
public class looper : MonoBehaviour
{
public AudioClip sound;
void Start()
{
audio.PlayOneShot(sound);
StartCoroutine(loop());
}
IEnumerator loop()
{
while(true)
{
yield return new WaitForSeconds(audio.clip.length);
audio.PlayOneShot(sound);
}
}
}
JS:
var sound : AudioClip;
function Start()
{
audio.PlayOneShot(sound);
loop();
}
loop()
{
while(true)
{
yield WaitForSeconds(audio.clip.length);
audio.PlayOneShot(sound);
}
}
This is using update, it does the same thing but does not instaniate a gameobject everytime
using UnityEngine;
using System.Collections;
public class AudioLoop : MonoBehaviour
{
public AudioClip sound;
void Start(){
audio.clip = sound;
audio.Play();
}
void Update()
{
if (!audio.isPlaying){
audio.Play()
}
}
}
or if you need JS
var sound : AudioClip
function Start(){
audio.clip = sound;
audio.Play();
}
function Update()
{
if (!audio.isPlaying){
audio.Play()
}
}
Mmm, I'm so sorry, but I just discovered that you can add an audio source component without any scripting... Anyway, thanks for the help!
– shlomito36
Why PlayOneShot? Also this can be done easy in Update aswell.
– EliteMossythank you!
– shlomito36But the audio plays very low, I can't hear it, why this happens?
– shlomito36