I have most of the enemy script done and working. If its health reaches zero the DIE function runs and the gameobject is destroyed while a death effect plays for one second. I am brain-farting on the part where I add an audio source to this part.
I have a variable to hold the audio source
public AudioSource SoundToPlay;
I am grabbing it in Start
SoundToPlay = GetComponent<AudioSource>();
And where I trigger the die function I have it set to play
health -= damage;
if(health <= 0)
{
Die();
SoundToPlay.Play();
Yet it wont play. I have the slots filled in the inspector. I tried placing the audiosrouce component on the enemy and then the camera. I can play the sound file just fine from the asset itself but it just wont play when the enemy dies.
Here is the entire script if this helps
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour {
public float speed;
public float rotSpeed;
public float shootingRange;
public float retreatRange;
public int health = 100;
public GameObject deathFX;
public AudioSource SoundToPlay;
public float timeBtwShots;
public float startTimeBtwShots;
public GameObject projectile;
public Transform firePoint;
public Transform player;
// Use this for initialization
void Start ()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
timeBtwShots = startTimeBtwShots;
SoundToPlay = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update ()
{
RotateTowards(player.position);
if (Vector2.Distance(transform.position, player.position) > shootingRange)
{
transform.position = Vector2.MoveTowards(transform.position, player.position, speed * Time.deltaTime);
}
else if(Vector2.Distance(transform.position, player.position) < shootingRange && Vector2.Distance(transform.position, player.position) > retreatRange)
{
transform.position = this.transform.position;
}
else if(Vector2.Distance(transform.position, player.position) < retreatRange)
{
transform.position = Vector2.MoveTowards(transform.position, player.position, -speed * Time.deltaTime);
}
if(timeBtwShots <= 0)
{
Instantiate(projectile, firePoint.position, transform.rotation);
timeBtwShots = startTimeBtwShots;
}
else
{
timeBtwShots -= Time.deltaTime;
}
}
private void RotateTowards(Vector2 target)
{
Vector2 direction = (target - (Vector2)transform.position).normalized;
var angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
var offset = -90f;
transform.rotation = Quaternion.Euler(Vector3.forward * (angle + offset));
}
public void TakeDamage(int damage)
{
health -= damage;
if(health <= 0)
{
Die();
SoundToPlay.Play();
}
}
void Die()
{
GameObject deathMarker = Instantiate(deathFX, transform.position, Quaternion.identity);
Destroy(gameObject);
Destroy(deathMarker, 1f);
}
}