I am using different animations/assets than the ones provided (which has been a headache, but a good learning experience)
My problem is after this lecture my player character is doing an extra 3/4 of the attack animation after the enemy has died, before snapping back to the idle animation.
If I set the triggers manually in play mode, the stopAttack works as intended, but seems to not being called fast enough in the code to stop the animation playing on death.
I have tried Resetting the attack trigger before triggering the stopAttack trigger but without success (making me believe it is simply being called too late for some reason).
Fighter.cs code:
using System;
using RPG.Core;
using RPG.Movement;
using UnityEngine;
namespace RPG.Combat
{
public class Fighter : MonoBehaviour, IAction
{
[SerializeField] private float weaponRange = 2f;
[SerializeField] private float timeBetweenAttacks = 1f;
[SerializeField] private float weaponDamage = 10f;
private Health _target;
private Mover _mover;
private float timeSinceLastAttack = 0;
private void Start()
{
_mover = GetComponent<Mover>();
}
private void Update()
{
timeSinceLastAttack += Time.deltaTime;
if (_target == null) return;
if (_target.IsDead()) return;
if (_target != null && !IsInRange())
{
_mover.MoveTo(_target.transform.position);
}
else
{
_mover.Cancel();
AttackBehaviour();
}
}
private void AttackBehaviour()
{
if (timeSinceLastAttack >= timeBetweenAttacks)
{
GetComponent<Animator>().SetTrigger("attack");
timeSinceLastAttack = 0f;
}
}
private bool IsInRange()
{
return Vector3.Distance(_target.transform.position, transform.position) < weaponRange;
}
public void Attack(CombatTarget combatTarget)
{
GetComponent<ActionScheduler>().StartAction(this);
_target = combatTarget.GetComponent<Health>();
}
public void Cancel()
{
GetComponent<Animator>().SetTrigger("stopAttack");
_target = null;
}
//animation event
void Hit()
{
_target.TakeDamage(weaponDamage);
}
}
}
Any advice appreciated.
Update 1: With some debug logs, it seems “Cancel” is never being called at all! Which does make me wonder how things are still mostly working!
Update2: I think I was getting confused between the 2 things done in this lecture, but I am now wondering why the lecturers code works. We call Cancel() when we move away from the target, but never try and call it once something is dead, so if the animation starts before the update is called, the animation will not be force stopped.
I tried updating the IsDead check to:
if (_target.IsDead())
{
Cancel();
return;
}
Though this didn’t work