amulbhatia amulbhatia - 3 months ago 24
C# Question

Detect Collision in Animation Event

I have animation Clip for swinging sword. At a specific frame, I added Event. I want when player swing sword, in that case only the enemy could die.

So I added the following

OnTriggerEnter
Code

void OnTriggerEnter(Collider col)
{
hit = true;
if (hit)
{
if (col.GetComponent<Collider>().tag == "enemy")
{
Destroy(col.gameObject);
}
}
}


When I try to add function OnTriggerEnter (in animation Clip) as animation Event, it is asking me to pass Collider parameter, Which i am not able to add.

Here is the screen shot of Add Event

Please help me , how can I add event with collider ( as parameter ) at a specific frame.. Thanks

SP. SP.
Answer

Collision and Trigger events are called on their own on every frame.

Call another public method from animation event for your task and put necessary Boolean or Enum there to control collision, trigger after swinging the sword.

public void SwingingSword()
{
 isSwingingSword = true; // make it false when not swinging the sword.
}

void OnTriggerEnter(Collider col)
{
  hit = true; // not sure what it's job here

  if (isSwingingSword && hit)
  {
   if (col.GetComponent<Collider>().tag == "enemy")
   {
    Destroy(col.gameObject);
   }
  }
}