C# 不能每秒播放声音?

C# 不能每秒播放声音?,c#,unity3d,C#,Unity3d,仅当启用特定脚本时,我希望每秒播放一次音频源: public int wait = 1; bool keepPlaying = true; void Start () { StartCoroutine(SoundOut()); } IEnumerator SoundOut() { while (keepPlaying) { if (GameObject.FindWithTag ("GameObject").GetComponent<Specif

仅当启用特定脚本时,我希望每秒播放一次音频源:

public int wait = 1;
bool keepPlaying = true;

void Start () 
{
    StartCoroutine(SoundOut());
}

IEnumerator SoundOut()
{
    while (keepPlaying)
    {
        if (GameObject.FindWithTag ("GameObject").GetComponent<SpecificScript> ().enabled == true)
        {
            GameObject.FindWithTag ("GameObject").GetComponent<AudioSource> ().Play ();  
            yield return new WaitForSeconds (wait);
        }
    }
}
public int wait=1;
bool keepPlaying=true;
无效开始()
{
start例程(SoundOut());
}
IEnumerator探测()
{
同时(继续播放)
{
if(GameObject.FindWithTag(“GameObject”).GetComponent().enabled==true)
{
GameObject.FindWithTag(“GameObject”).GetComponent().Play();
产生返回新WaitForSeconds(等待);
}
}
}
启用特定脚本时,此脚本不会每秒播放声音。有什么问题吗

尝试使用

float wait=1;
bool keepPlaying=true;
void Start()
{
start例程(SoundOut());
}
IEnumerator探测()
{
同时(继续播放)
{
if(GameObject.FindWithTag(“GameObject”).GetComponent().enabled==true)
{
AudioSource myAudioSource=GameObject.FindWithTag(“GameObject”).GetComponent();
myAudioSource.PlayOneShot(myAudioSource.clip);
产生返回新WaitForSeconds(等待);
}
}
}
使用此技术,如果剪辑>1秒,它们将重叠

如果您不想这样做,只需执行myAudioSource.Stop();再次播放之前。

尝试使用

float wait=1;
bool keepPlaying=true;
void Start()
{
start例程(SoundOut());
}
IEnumerator探测()
{
同时(继续播放)
{
if(GameObject.FindWithTag(“GameObject”).GetComponent().enabled==true)
{
AudioSource myAudioSource=GameObject.FindWithTag(“GameObject”).GetComponent();
myAudioSource.PlayOneShot(myAudioSource.clip);
产生返回新WaitForSeconds(等待);
}
}
}
使用此技术,如果剪辑>1秒,它们将重叠


如果您不想这样做,只需执行myAudioSource.Stop();再次播放之前。

返回新的WaitForSeconds(carwait)
什么是
carwait
?@Valentin抱歉,我的错误。我编辑了这个问题。但它有什么作用吗?这是完全错误的,派克。只需使用
invokererepeating
即可。所以它只是
调用重复(“Playit”,.1f,2f)private void Playit(){blah.Play();}
返回新的WaitForSeconds(carwait)
carwait是什么?@Valentin抱歉,我的错误。我编辑了这个问题。但它有什么作用吗?这是完全错误的,派克。只需使用
invokererepeating
即可。所以它只是
调用重复(“Playit”,.1f,2f)private void Playit(){blah.Play();}
float wait = 1;
bool keepPlaying = true;

void Start()
{
    StartCoroutine(SoundOut());
}

IEnumerator SoundOut()
{
    while (keepPlaying)
    {
        if (GameObject.FindWithTag("GameObject").GetComponent<SpecificScript>().enabled == true)
        {
            AudioSource myAudioSource = GameObject.FindWithTag("GameObject").GetComponent<AudioSource>();
            myAudioSource.PlayOneShot(myAudioSource.clip);
            yield return new WaitForSeconds(wait);
        }
    }
}