我正在制作塔防游戏。我想发出滴答滴答的倒计时声音,但是当我在代码中调用“播放声音”功能时,它只会无限循环。我也用了协程,但没有用。请帮助我。
==================================== = ==================
波动扳手
public float timeBetweenWaves = 34f;
private float countdown = 34f;
void Update()
{
if (waveNumber <= 40)
{
SpawnCount();
}
}
void SpawnCount()
{
GameObject[] enemyFind = GameObject.FindGameObjectsWithTag("Enemy");
int enemyCount = enemyFind.Length;
if (enemyCount == 0) // if enemy is 0, countdown goes 34 to 0
{
if (countdown <= 0f) // if countdown becomes 0, wave starts and countdown stops at 34
{
StartCoroutine(SpawnWave()); // wave starts here
countdown = timeBetweenWaves; // countdown initializes
}
countdown -= Time.deltaTime; // countdown goes 34 to 0
waveCountDownText.text = Mathf.Round(countdown).ToString();
// I want to play countdown tick-tock sound here until countdown becomes 0
//FindObjectOfType<SoundManager>().Play("Timer"); // this didn't work
}
}
声音管理器
public Sound[] sounds;
public static SoundManager instance;
void Awake()
{
if (instance == null)
{
instance = this;
}
else
{
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
foreach (Sound s in sounds)
{
s.source = gameObject.AddComponent<AudioSource>();
s.source.clip = s.clip;
s.source.volume = s.volume;
s.source.pitch = s.pitch;
s.source.loop = s.loop;
}
}
void Start()
{
Play("Theme");
}
public void Play (string name) // i used this function and sound name is "Timer"
{
Sound s = Array.Find(sounds, sound => sound.name == name);
if (s == null)
{
Debug.LogWarning("Sound: " + name + "Not Found!");
return;
}
s.source.Play();
}
答案 0 :(得分:0)
尝试使用AudioSource
public AudioSource[] audioSource;
public AudioClip[] clips;
audioSource [source].clip = clips [0];
audioSource[source].Play ();
也请阅读此内容,它可能会帮助Unity: Difference between Audio Source, Audio Listener and Audio Clip
答案 1 :(得分:0)
我会做这样的事情。如果您添加此代码,则可能会更容易,只需将滴答数组中的滴答声和滴答声更改为所需的内容即可。
public class Clock : MonoBehaviour
{
AudioSource audioS;
public AudioClip[] ticking;
void Start()
{
audioS = gameObject.AddComponent<AudioSource>();
StartCoroutine(TickingClock());
}
public bool tick = true;
IEnumerator TickingClock()
{
int x= 0;
while(tick)
{
x++;
if(x % 2 == 0)
{
audioS.PlayOneShot(ticking[0], 1f);
}
else
{
audioS.PlayOneShot(ticking[1], 1f);
}
yield return new WaitForSeconds(0.5f);
}
}
}
要关闭刻度线,您只需要将布尔值设为false即可:)。 如果您想在任何时候都需要调用,则可能需要在调用时创建一个新的触发方法。
类似。
// call this from a game Controler script :)
public void CallClock(){
StartCoroutine(TickingClock());
}