It’s my bad. My code is quite different from the course because I don’t like switch statements, so I have an actual state machine, and I didn’t like the fact that the UnitAnimator
was spawning projectiles. Wasn’t paying attention to the damage happening as soon as the shoot happens.
My own project uses a bow and arrow and the arrows are slower than the really-fast bullets from the course. What I did was to add a state between State.Shooting
and State.CoolOff
(call it State.Damage
). The Shoot
state waits long enough for the arrow to reach the target before transitioning to the Damage
state. This does the damage and immediately moves to the CoolOff
state
Here I have adapted the course’s code with the damage state. I’ve made comments about what is what
private enum State
{
Aiming,
Shooting,
Damage, // I added this to do the damage
Cooloff,
}
private void Update()
{
if (!isActive)
{
return;
}
stateTimer -= Time.deltaTime;
switch (state)
{
case State.Aiming:
Vector3 aimDir = (targetUnit.GetWorldPosition() - unit.GetWorldPosition()).normalized;
float rotateSpeed = 10f;
transform.forward = Vector3.Lerp(transform.forward, aimDir, Time.deltaTime * rotateSpeed);
break;
case State.Shooting:
if (canShootBullet)
{
Shoot();
canShootBullet = false;
}
break;
case State.Damage:
targetUnit.Damage(40); // here we do the damage
break;
case State.Cooloff:
break;
}
if (stateTimer <= 0f)
{
NextState();
}
}
private void NextState()
{
switch (state)
{
case State.Aiming:
state = State.Shooting;
float shootingStateTime = 0.1f; // <-- This is how long you will wait before the damage state
stateTimer = shootingStateTime;
break;
case State.Shooting:
state = State.Damage;
float damageStateTime = 0f; // No need to linger. We'll do damage and move on
stateTimer = damageStateTime;
break;
case State.Damage:
state = State.Cooloff;
float coolOffStateTime = 0.5f;
stateTimer = coolOffStateTime;
break;
case State.Cooloff:
ActionComplete();
break;
}
}
And if you’re still reading, I’ll answer your question:
You have the enemy. Just get its unit and do damage
private void OnTriggerEnter(Collider other)
{
if(other.tag == "Enemy")
{
Debug.Log("Hit Enemy");
if (other.TryGetComponent<Unit>(out var unit))
{
unit.Damage(40);
}
}
else
{
Debug.Log("Hit something else");
}
}