Hi, my enemy prefab has attached an AudioSource with a clip inside, and then i wrote a script to play that sound when the enemy dies, but the audio is not playing.
Here’s the code:
public class health : MonoBehaviour
{
public AudioSource death;
public float startingHealth;
public float currentHealth { get; private set; }
public bool isDead;
[Header(“iFrames”)]
public float iFrameDuration; //tempo invulnerabilità dopo essere stato colpito
public int numberOfFlashes; //numero di flash dopo invulnerabilità
private SpriteRenderer spriteRend; //usato per determinare il colore appena viene colpito
// Start is called before the first frame update
private void Awake()
{
currentHealth = startingHealth;
spriteRend = GetComponent();
}
// Update is called once per frame
void Update()
{
if (isDead)
{
death.Play();
Destroy(this.gameObject);
}
}
public void takeDamge(float damage)
{
currentHealth = Mathf.Clamp(currentHealth - damage, 0, startingHealth);
if(this.tag == “Player”)
StartCoroutine(Invulnerability());
//vediamo se la vita è finita o no
if (currentHealth > 0)
{
//playerHurt
//riga di animazione di danni
//riga iframes
}
else
{
if (!isDead)
{
//riga di animazione di morte
//GetComponent().enabled = false; //disattiva movimento del giocatore
isDead = true;
}
}
}
public void AddHealth(float _valore)
{
currentHealth = Mathf.Clamp(currentHealth + _valore, 0, startingHealth);
}
private IEnumerator Invulnerability() //da capire cosa è IEnumerator
{
Physics2D.IgnoreLayerCollision(6, 7, true); //metti i due layer come parametri che non devono collidere (così che magari non trapassa i muri), che sono player e enemy
//durata invulnerabilità
for (int i = 0; i < numberOfFlashes; i++)
{
spriteRend.color = new Color(1, 0, 0, 0.5f); //cambio colore in rosso
yield return new WaitForSeconds(iFrameDuration / (numberOfFlashes * 2)); //così si aspett aprima che il codce fa eseguire la prossima linea di codice
spriteRend.color = new Color(255, 255, 0, 255);
yield return new WaitForSeconds(iFrameDuration / (numberOfFlashes * 2));
}
spriteRend.color = new Color(255, 255, 255, 255);
Physics2D.IgnoreLayerCollision(6, 7, false); //rimetti le collisionià
}
}
[/code]