player death sound not playing
i got my hurt sound to work when ever i come into contact with a spike but am not really sure why my death sound is not working
public class playerHealth : MonoBehaviour {
// declareing health variables
public float maxHealth;
private float currentHealth;
// declareing audio variables
public AudioClip playerDieing;
public AudioClip[] hurt;
public GameObject deathFX;
// delcareing component variables
private playerController controllerMovement;
public AudioSource playerAS;
// declareing hud variables
public Image healthSlider;
public Image damageScreen;
private Color damagedColor = new Color(255f, 255f, 255f, 0.5f);
private bool damaged = false;
private float smoothColor = 5f;
void Start () {
// health instalization
currentHealth = maxHealth;
// component instalization
controllerMovement = GetComponent<playerController>();
playerAS = GetComponent<AudioSource>();
// hud instalization
healthSlider.fillAmount = maxHealth;
damaged = false;
}
// Update is called once per frame
void Update () {
// if player is damaged then show the damage screen else make the damage screen disapper adjusting the alpha using lerp and deltatime
if(damaged) {
damageScreen.color = damagedColor;
} else {
damageScreen.color = Color.Lerp(damageScreen.color, Color.clear, smoothColor * Time.deltaTime);
}
// setting damaged equal to false
damaged = false;
}
// controls if the player is being damaged if so then how much damage and what happens when the player takes damage
public void addDamge(float damage) {
if(damage <= 0) {
return;
}
currentHealth -= damage;
playerAS.PlayOneShot(hurt[Random.Range(0,hurt.Length)]);
healthSlider.fillAmount = currentHealth / 100;
damaged = true;
if(currentHealth <= 0) {
playerAS.PlayOneShot(playerDieing);
makeDead();
}
}
public void makeDead() {
Instantiate(deathFX, controllerMovement.transform.position, transform.rotation);
Destroy(gameObject);
}
}
Answer by jgodfrey · Jun 29, 2016 at 11:30 PM
I'd guess your game object is being destroyed before the sound finishes playing. So, you either need to 1) play the sound from some other class (like an AudioManager or similar), or 2) delay the destruction of your game object until after the sound has completed.
Option #1 is probably a better design, but also likely requires more radical changes to your current design.
For option #2, you might be able to get away with immediately destroying the components you don't need anymore (for instance, the renderer to "hide" the object). But, delay the destruction of the main object until the clip completes. You can pass in an optional time value to Destroy to delay the destruction for a predetermined amount of time. In your case, you could pass in the length of your audioClip (accessed via the "length" property of the audioClip) as the delay. Or, just pass in a static value that's "long enough" if you want...