Melee attacking, using force and health values

Hi there

I only know the sheer basics of scripting in C# so i don't know how to approach this.

Basically, When the left mouse button is pressed, it plays a melee animation.

Now what i want to happen is that if the distance of an enemy is lower than lets say 10, for the health value of the enemy to decrease and the enemy knocked back from force.

Not only that, i want all this to happen at a certain point in the animation. The animation is a Spear swinging back, then lunging foward for the attack. So basically what i want is that the health value decreases once the animation reaches a certain frame or point in time.

Much Appreciated

You could split up your animation, into lets say "swingAttackPart1" and "swingAttackPart2". swingAttackPart1 should go to the frame where you want the health of the enemy to decrease / knock enemy back.

In code, you'd then start playing swingAttackPart1, wait for it to finish, then once it's finished, you'd be at the correct point in time. Then you'd just decrease the health, and simultaneously play swingAttackpart2 as well as possibly a "gettingHit" animation for the enemy.

It would look something like this:

    GameObject enemyGameObject=GameObject.Find("enemy");

    If (distance <= 10) {
    yield return StartCoroutine(swingPart1); //"Yield return" makes sure code execution doesn't continue until the coroutine is finished.
    gameObject.animation.Play("swingPart2"); //Now that swingPart1 has finished, we can play the "gettingHit" animation of enemy, and decrease enemies health.
    DecreaseHealthOfEnemy(); //Function that decreases enemy health

The coroutine would look like

Ienumerator swingPart1() {
gameObject.animation.Play("swingPart1"); //Start animation
while (gameObject.animation.IsPlaying()) { //Loop that checks if the animation is still running. If it is, "yield return null", skips a frame, and run the loop again)
yield return null;

As an alternative, you could keep the swingAttack in one animation, and then make a counter in the above coroutine that skips a frame until you've reached the frame number you want. Like so:

Ienumerator swingAnimation() {
gameObject.animation.Play("swing"); //Start animation
int frameToStopAt=30;
for (int i=0; i < frameToStopAt; i++) { 
yield return null;

In this case, you'd remove gameObject.animation.Play("swingPart2"); in the parent method. The code ain't tested, but it should give you the general idea.