lapezi prod.
lapezi prod.

Reputation: 3

Sound not playing on last hit

I have a problem which is that my hurt sound doesn't play on last hit. On other hits it works very well. I think that its because of the gameObject getting destroyed. I have tried it by putting the script to my bullet and changing the tag. Also the Debug.Log works perfectly on last hit. I hope that somebody could help me.

Anyway, here's my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class HealthSystem : MonoBehaviour
{
    
    public AudioSource source;
    
    public AudioClip clip;
    
    public Image healthBar;

    public float healthAmount = 100;

    public GameObject bullet;
    

    void Start()
    {

    }
    private void Update()
    {
        if(healthAmount <= 0)
        {
            Destroy(gameObject);
        }
    }

    public void TakeDamage(float Damage)
    {
        source.PlayOneShot(clip);
        healthAmount -= Damage;
        healthBar.fillAmount = healthAmount / 100;
    }

    public void Healing(float healPoints)
    {
        healthAmount += healPoints;
        healthAmount = Mathf.Clamp(healthAmount, 0, 100);

        healthBar.fillAmount = healthAmount / 100;
    }
    
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Bullet"))
        {
            if (!source.isPlaying)
            {
                Debug.Log("i have are played");
                TakeDamage(20);
            }
        }
    }
}

Upvotes: 0

Views: 37

Answers (1)

Tatranskymedved
Tatranskymedved

Reputation: 4371

Exactly as you said: Because your game object is getting destroyed with last bullet, the AudioSource is getting destroyed with it and it cannot play whole sound. What is the workaround? There are 2, you can either:

  • Spawn new GameObject just to play the sound and destroy it right after
  • Hide/disable the object (as if it is destroyed), play the sound and once sample is played, destroy it

Upvotes: 1

Related Questions