简体   繁体   中英

Multi attack in unity

I'm trying to play 3 different attack in unit when the user presses the same bottom multiple time the attack will change. I tried this code it's ok but failed to track the number of attack

if (Input.GetKeyDown(KeyCode.Q) && attTraking == 0)
{
    anim.SetTrigger(attackOneToHash);
    attTraking = 1;
}

else if (Input.GetKeyDown(KeyCode.Q) && attTraking == 1)
{
    anim.SetTrigger(attackTwoToHash);
    attTraking = 2;

}

else if (Input.GetKeyDown(KeyCode.Q) && attTraking == 2)
{
    anim.SetTrigger(attackThreeToHash);
    attTraking = 0;
}

Then I add else and set attTraking to 0 the code failed to exit the first IF statement.

You haven't shown the full class, so it hard to tell.

Nevertheless, my guess is that attTraking is reset to zero each time because

  • you declared it local to the function (it should be declared at class level)
  • you reset it to zero somehow before the method has the time to be called a second / third time.

If you add an else statement like this one :

else 
{
    attTraking = 0;
}

then attTracking will be reset to zero at any update where the key 'Q' is not pressed (which completely invalidate your logic of "press the key multiple times"

Pac0's answer is correct for your scenario, but I just wanted to chime in and say there's a better way to do this..

int maxCount = 2;
int attCount = 0;
public int[] AttackTriggers; //Add the trigger ID's to the array via the editor.
public float attackResetTime = 1.0f; //Will take one second to reset counter.

if(Input.GetKeyDown(KeyCode.Q))
{
  anim.SetTrigger(AttackTriggers[attCount]);
  attCount++;
  if(attCount > maxCount)
  {
     attCount = 0;
  }
}

But then you will need to check to see if you should reset your attCount back to 0 if the user hasn't pressed Q in a specified amount of time. This can be achieved with Coroutines.

public IEnumerator ResetAttCount()
{
   yield return new WaitForSeconds(attackResetTime);
   attCount = 0;
}

Now, we can reset the count based on time, but we still need to make sure we start and stop the coroutine in the right places, so let's modify the original if statement a bit:

if(Input.GetKeyDown(KeyCode.Q))
{
  StopCoroutine(ResetAttCount());
  anim.SetTrigger(AttackTriggers[attCount]);
  attCount++;
  if(attCount > maxCount)
  {
     attCount = 0;
  }
}

And then let's add one more statement for the Key Up event:

if(Input.GetKeyUp(KeyCode.Q))
{
  StartCoroutine(ResetAttCount());
}

No now we are successfully timing the reset of the attack count by starting the timer when the key is released and stopping once the key has been pressed again within one second.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM