Unity C# 按键播放动画一次

huangapple go评论64阅读模式
英文:

Unity C# Play an animation once on key

问题

我有2个名为"attacking_1"和"attacking_2"的攻击动画,我希望在玩家按下"C"键一次时随机播放其中一个。我希望动画能够一直播放到最后一帧,而玩家无需一直按住C键。

这是我的代码,目前的情况是这段代码在每一帧都被执行,导致我的角色在按下一次C键时显示两个攻击动画。

我不明白的是,为什么if语句会执行多次,即使玩家只按下一次C键。

if (Input.GetKey(KeyCode.C))
{
    int random = Random.Range(1, 3);
    Debug.Log(random);
    anim.SetBool("attacking_" + random.ToString(), true);
}
英文:

I have 2 attack animations named "attacking_1" and "attacking_2", I want to play one at random when player presses "C" key once. I want the animation to continue to play to last frame of it without player needing to hold down the C key.

Here's my code and what's happening is that this code is ran every frame and making my player display both attack animations on one C key press.

What I don't understand is why the if statement is executing many times even tho the player only press the C key once.

   if (Input.GetKey(KeyCode.C))
    {
        int random = Random.Range(1, 3);
        Debug.Log(random);
        anim.SetBool("attacking_" + random.ToString(), true);
    }

答案1

得分: 1

"Input.GetKey()"
检查按钮是否在每一帧按下,并在每一帧运行。你需要的是
"Input.GetKeyDown()"
它只在第一帧按下时运行。希望对你有所帮助!

英文:

"Input.GetKey()"
Checks if a button is pressed down every frame and runs it every frame. What you need is
"Input.GetKeyDown()"
Which only runs it the first frame it's pressed down

Hope this helps!

huangapple
  • 本文由 发表于 2023年2月24日 14:15:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75553165.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定