- Home /
How can I delay dealing damage?
When clicking LMB, the Attack function below is called. However, in its current implementation, it sends the ApplyDamage message instantly and I would like it to wait half a second so that the damage can be applied in sync with the animation. Code below:
void Attack()
{
if (Time.time > nextAttack)
{
Collider[] colliders = Physics.OverlapSphere(transform.position, AttackRange);
foreach (Collider hit in colliders)
{
if (hit.tag == "Enemy" && Vector3.Distance(hit.transform.position, transform.position) <= AttackRange)
{
hit.SendMessage("ApplyDamage", AttackDamage);
}
}
nextAttack = Time.time + AttackRate;
}
}
I would have liked to use Invoke but I cannot pass the hit Collider through Invoke. I also thought about making a global variable but by the time the Invoked function could execute, the global variable might have changed as the for loop searched for enemies. It looks like my only option is to make a global array of Colliders, add a Collider to the array when it detects and enemy and after searching, send the ApplyDamage message to all Colliders in the list. Is there a better way to do this?
Answer by ByteSheep · Mar 04, 2012 at 06:56 AM
If you are already triggering the animation then you can go to your animation window and add an event that calls the function as soon as the animation has gotten to a certain point. To do all this just go to window > Animation and select your animation.. then double click or right click just under the timeline to add an event which will call a function, you can then specify which function should be called. This should work well for your purpose I think :)
Ahh I didn't know you could do that in the Animation window. I'll read up on it, thanks :D
Your answer
Follow this Question
Related Questions
Damage sending with grenades. 1 Answer
SendMessage is working but the variable is not being updated on the other end 1 Answer
SendMessage vs MethodInfo.Invoke 1 Answer
Repeating Damage sendMessage 1 Answer
Send Message Not sending 2 Answers