Search Unity

Question Scripting combo system

Discussion in 'Scripting' started by polluxik, Oct 20, 2022.

  1. polluxik

    polluxik

    Joined:
    Aug 17, 2017
    Posts:
    11
    Hi, I am not sure if this goes to "animation" category or here but I have 2 events in animation called "EnableSecondAttack" and "DisableSecondAttack" then I just execute OnAttack(). Is this good approach or there is better solution ? If yes how I should do combo system ?

    Code (CSharp):
    1. bool canDoSecond = false;
    2. private void OnAttack()
    3.         {
    4.             if (_input.attack && !canDoSecond)
    5.             {
    6.                 _animator.SetTrigger(_animIDAttack1);
    7.                 _input.attack = false;
    8.                
    9.             }
    10.             else if (_input.attack && canDoSecond)
    11.             {
    12.                 _animator.SetTrigger(_animIDAttack2);
    13.                 _input.attack = false;
    14.                 canDoSecond = false;
    15.             }
    16.             else _animator.ResetTrigger(_animIDAttack2);
    17.         }
    18. private void EnableSecondAttack()
    19.         {
    20.             canDoSecond = true;
    21.            
    22.         }
    23. private void DisableSecondAttack()
    24.         {
    25.             canDoSecond = false;
    26.         }
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,910
    I recommend learning the "state machine" programming pattern. It maps extremely well to problems like this. Each of your if/else if blocks here would be represented by a state, and rather than having a messy spaghetti of variables like
    canDoSecond
    , you just track the current state of the state machine you're in.
     
  3. polluxik

    polluxik

    Joined:
    Aug 17, 2017
    Posts:
    11
    Thank you for you reply, you are right, state machine is better, I tried to do it and it is better.