- Home /
Question by
Faiz_Abdullah · Mar 03, 2020 at 01:12 PM ·
c#enemyaudiosourcesound effects
Play sound when enemy chase
I try to make whenever enemy is chasing player, a chase theme will play. I've tried the same exact method for sound such as flashlight and it works just fine. But this one didn't work somehow.
private AudioSource chaseSound;
void Start()
{
enemyAnim = GetComponent<Animator>();
target = FindObjectOfType<PlayerMovement>().transform;
chaseSound = GetComponent<AudioSource>();
}
void Update()
{
//set a range to follow player
if (Vector3.Distance(target.position, transform.position) <= maxRange && Vector3.Distance(target.position, transform.position) >= minRange)
{
FollowPlayer();
}
else if (Vector3.Distance(target.position, transform.position) >= maxRange)
{
ReturnPosition();
}
}
public void FollowPlayer()
{
enemyAnim.SetBool("isMoving", true);
enemyAnim.SetFloat("xDirection", (target.position.x - transform.position.x));
enemyAnim.SetFloat("yDirection", (target.position.y - transform.position.y));
//current position, target position, speed to move
transform.position = Vector3.MoveTowards(transform.position, target.transform.position, speed * Time.deltaTime);
chaseSound.Play();
}
Comment
Answer by Sxythe · Mar 03, 2020 at 01:49 PM
The FollowPlayer function gets called in the Update, meaning if the enemy is chasing, the chaseSound will repeatedly start playing. Try putting it in an if statement, to check if it's playing or not.
if (!chaseSound.isPlaying)
{
chaseSound.Play();
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612224322im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Sound plays right at the beginning 2 Answers
How to destory gameObject without destroying the audio source attached to it? 2 Answers
Audio Clip Playing every frame 2 Answers