C# 如何使用GetKeyDown函数?
我正在学习一个关于健康条和法力受GetKeyDown函数影响的教程。由于某种原因,当我按下“I”或“O”时,什么也没有发生。甚至我的角色动作都是不动的 我尝试过回溯,甚至改变健康数据。本教程来源于此C# 如何使用GetKeyDown函数?,c#,unity3d,C#,Unity3d,我正在学习一个关于健康条和法力受GetKeyDown函数影响的教程。由于某种原因,当我按下“I”或“O”时,什么也没有发生。甚至我的角色动作都是不动的 我尝试过回溯,甚至改变健康数据。本教程来源于此 如果我正确理解您的问题,则在Update()函数中调用该函数应该会产生所需的结果 编辑:删除不必要的响应听起来您的函数调用不正确。从未在Unity中工作过,但我在XNA中,您必须在更新中调用GetInput()函数。Unity可能有某种程度的automagic功能,但如果有,它似乎不起作用。谢谢@克
如果我正确理解您的问题,则在Update()函数中调用该函数应该会产生所需的结果
编辑:删除不必要的响应听起来您的函数调用不正确。从未在Unity中工作过,但我在XNA中,您必须在更新中调用
GetInput()
函数。Unity可能有某种程度的automagic功能,但如果有,它似乎不起作用。谢谢@克里斯托弗我现在唯一的问题是“我”和“O”没有注册,但我把我的移动回来了谢谢!你好,多莉,欢迎来到SO。您的答案使用Update方法部分回答了问题。然而,答案中最重要的部分是关于如何重构代码。这没有被问到,可能会让人困惑。请尽量将答案集中在问题上,以便其他有类似问题的用户可以轻松找到解决方案。谢谢:)谢谢,我已经更新了我的答案,删除了不必要的重构部分
[SerializeField]
private Stat health;
[SerializeField]
private Stat mana;
private float initHealth = 100;
private float initMana = 50;
protected override void Start()
{
health.Initialize(initHealth, initHealth);
mana.Initialize(initMana, initMana);
base.Update();
}
private void GetInput()
{
direction = Vector2.zero;//reset direction
if (Input.GetKeyDown(KeyCode.I))
{
health.MyCurrentValue -= 10;
mana.MyCurrentValue -= 10;
}
if (Input.GetKeyDown(KeyCode.O))
{
health.MyCurrentValue += 10;
mana.MyCurrentValue += 10;
}
if (Input.GetKeyDown(KeyCode.W))
{
direction += Vector2.up;
}
if (Input.GetKeyDown(KeyCode.A))
{
direction += Vector2.left;
}
if (Input.GetKeyDown(KeyCode.S))
{
direction += Vector2.down;
}
if (Input.GetKeyDown(KeyCode.D))
{
direction += Vector2.right;
}
}
}