In my top-down RPG, I have several enemies like Goblins, Trolls, Dragons,…
Each of them have two variables:
baseAttackDuration = float (how long in seconds does attack take, varies between enemies)
increasedAttackSpeed = float (attack speed modifier, may change during combat, also varies between enemies)
So when the character attacks, the duration of the attack equals to:
attackDuration = baseAttackDuration / increasedAttackSpeed
Question:
Now, how should I set Mecanim to play attack animation so the animation lines up with in game logic and lasts exactly attackDuration?
As you can see in this thread you can connect an animation clip speed to an animator parameter. In the animator state machine select a state with a clip assigned and you should see this:

In the image above you can see that there is a parameter called “MySpeed” in the layer, and this has been chosen as a speed multiplier for the animation clip in question. You’ll need to tweak the values to fit your “duration”.
Depending on your scenario, if you just need to wait to a specific point in the clip to e.g. apply damage, I would only set the speed and setup an event in the animation clip. Add the event at the point where you want to apply damage as described in the manual here.
If you need to know how to set animator parameters in code read the manual on Animation Parameters
This is the easiest way to do it. If you need to have more direct control there is a button in the image with the text “Add Behaviour”. This will allow you to add a behaviour to this animation state. In this behaviour you can override several events such as “OnStateEnter”. See the manual on State Machine Behaviours and this tutorial.