Hello I'm trying to stop a sound from repeatedly playing on my GetKey command, while the button is hold the sound will play over and over although I only want it to play once every few seconds otherwise the sound gets really loud and irritating, I've tried to create a cooldown using a coroutine and it's not working, also if I put audio.Stop() in the IEnumerator then the sound doesn't play at all.
Here's my code.
using UnityEngine;
using System.Collections;
public class JumpScript : MonoBehaviour {
Animator anim;
public AudioClip JumpSound;
public AudioClip SlidingSound;
public float jumpSpeed = 1000f;
float jumpRate = 1.2f;
bool canJump = true;
public float slideTime = 1.0f;
public float timeHeld;
void Start()
{
this.gameObject.AddComponent();
this.GetComponent().clip = JumpSound;
this.gameObject.AddComponent();
this.GetComponent().clip = SlidingSound;
anim = GetComponent();
}
void Update()
{
if (Input.GetKey(KeyCode.Space)) timeHeld += Time.deltaTime;
if (Input.GetKeyUp(KeyCode.Space) && timeHeld <= slideTime) TryJump();
if (Input.GetKey(KeyCode.Space) && timeHeld > slideTime) Slide();
timeHeld = 0f;
}
void TryJump()
{
if (!canJump) return;
Jump();
StartCoroutine(JumpCooldown());
}
IEnumerator JumpCooldown()
{
canJump = false;
yield return new WaitForSeconds(jumpRate);
canJump = true;
yield break;
}
IEnumerator SoundCooldown()
{
audio.Play();
yield return new WaitForSeconds(2);
audio.Stop();
}
void Jump()
{
audio.PlayOneShot(JumpSound);
rigidbody2D.AddForce(new Vector2(0, jumpSpeed));
anim.Play("Jumping");
}
void Slide()
{
audio.PlayOneShot (SlidingSound);
anim.Play("Sliding");
StartCoroutine(SoundCooldown());
}
}
↧