Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Animation loop & trigger collision

Discussion in '2D' started by Ademiz, Sep 22, 2023.

  1. Ademiz

    Ademiz

    Joined:
    Apr 16, 2021
    Posts:
    6
    Hi all,
    Here's my problem : I have a very simple animation looping over 3 frames. It's a sword swing animation.
    And I want the enemy health to deplete every time the it's hit at the 2nd frame.

    I've set a gameObject "attack" being the child of my "knight" asset and added a trigger collider, like so
    upload_2023-9-22_20-58-39.png
    the enemy has a non trigger circle collider. I added a OnHitEnable collider on the 3rd frame

    and here's my code for the trigger
    Code (CSharp):
    1. private void OnTriggerEnter2D(Collider2D collider)
    2. {
    3.  
    4.  
    5.     if (collider.CompareTag("Enemy"))
    6.     {
    7.  
    8.         stats = collider.GetComponent<Stat>();
    9.  
    10.         int health = stats.GetHealth();
    11.  
    12.         if (health <= 0)
    13.         {
    14.             //etc...
    So far the code has been triggering only once even though the animation loops correctly. But I'd like to enter the trigger more than once, to deplete heatlh by bits.

    1-Am I doing correctly so far ?
    2- Should I add an intermediate state after and and/or before so the animation collider resets and I can reenter the trigger?
     
    Last edited: Sep 22, 2023
  2. Cornysam

    Cornysam

    Joined:
    Feb 8, 2018
    Posts:
    1,343
    You probably want to use Animation events to enable/disable the collider at the moments of "impact". OnTriggerEnter will trigger once per collider Entrance. If you enable and disable it properly, it will re-trigger once per enable.

    Currently, your collider is probably always in contact with the enemy or object so it is triggering just once.
     
  3. Ademiz

    Ademiz

    Joined:
    Apr 16, 2021
    Posts:
    6
    Thanks for your answer ^^.
    That's my diagnosis too. The enemy is has entered the collder and that's it...

    But I already added OnHitEnableCollider on the 3rd frame, isn't that what it's supposed to do ?
    upload_2023-9-22_21-19-29.png
     
  4. Cornysam

    Cornysam

    Joined:
    Feb 8, 2018
    Posts:
    1,343
    When are you disabling it? You need to enable it on a down-swing or point of impact, then disable it. Then enable it again for the 2nd and 3rd attack, with the respective disables as well. So if you have 1 animation that has 3 sword swings, you need 3 enables and 3 disable animation events
     
  5. Ademiz

    Ademiz

    Joined:
    Apr 16, 2021
    Posts:
    6
    not even sure I'm disabling or enabling it. I'll check that way. Thanks a lot.