英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论