So basically the title. At first I though it was the InvokeRepeating method overriding the Audio Source, but even after removing the InvokeRepeating, the dead sound of my enemy continued playing seconds before it destroy itself, and not at the moment it gets killed. I did some tests changing the line of code to other place and nothing.
This is a part of my code so far:
void Start () {
InvokeRepeating("MakeSound", 1f, 10f);
}
void Update () {
if (currentHealth > 0f) //Mientras que la vida sea mayor a cero
{
if (canMove)
{
if (distance > 2)
{
ChasePlayer();
}
else if (canAttack && !PlayerHealth.playerHInstance.isDead)
{
Attack();
}
}
else
{
Idle();
}
}
else if (currentHealth <= 0f){
AudioSrc.clip = deadSound;
AudioSrc.Play();
currentHealth = 0f;
Dead();
}
}
void Dead(){
AnimController.SetBool("isDying", true);
navAgent.isStopped = true;
navAgent.ResetPath(); //Clears the current path
Destroy(this.gameObject, 5f);
}
At least I can’t see where the problem is, it is clear that I’m not aware of something.
It’s because you call Destroy with 5f which means the object won’t be destroyed until 5 seconds has passed. Update will continued to be called until the object is destroyed.
A simple fix would be to add a bool to say whether Dead() has been called already.
This works for sure. Alternately you can just disable this script with:
this.enabled = false;
That will stop all messages to it, EXCEPT collisions. Collisions still happen to allow waking up, but you can specifically guard against it by rechecking .enabled. But it does not appear you are using collisions.
That’s usually how you kill a controller when the destroy is gonna happen later.
Ohhhh, well, as you say, I don’t use collisions. Also, disabling the script means that it will no longer reproduce sounds, which is actually not convenient for me.