![](/img/trans.png)
[英]Is there a C# code in unity to identify when a Button is pressed and when it is released?
[英]Unity C# GetKey() not working when i set a variable with the button i want pressed in
我试图做到这一点,以便您可以通过统一本身而不是脚本分配您想让玩家跳跃/移动的任何键。 我想用每个键的键码设置公共变量,并使用这些键来启动功能。 它不适用于箭头键,我在 GetKey() 键码上找不到太多信息。 我知道您可以在项目设置中为每个操作设置一个键然后调用该操作,但我不想这样做。
这是我的代码://脚本名称是“Movement”,在对象上附加了一个刚体2D,重力为1.5,盒子collider2D
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public int JumpHeight;
public int MoveSpeed;
private Rigidbody2D rb;
public string JumpButton;
public string MoveRightButton;
public string MoveLeftButton;
// Start is called before the first frame update
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
private void Update()
{
if(Input.GetKeyDown(JumpButton))
{
rb.velocity = new Vector3(0, JumpHeight, 0);
}
if(Input.GetKey(MoveRightButton))
{
rb.velocity = new Vector3(MoveSpeed, 0, 0);
}
if(Input.GetKey(MoveLeftButton))
{
rb.velocity = new Vector3(MoveSpeed*-1, 0, 0);
}
}
}
您应该尝试对 Unity 输入使用KeyCode
类型而不是string
类型,以避免出现此类问题。 我建议简要阅读:
https://docs.unity3d.com/ScriptReference/KeyCode.html
了解更多关于可用的不同选项的信息。 在 Unity 检查器中,对于任何带有该移动脚本的对象,您将能够通过下拉菜单分配您希望使用的按钮。
Unity 以用户友好的方式处理枚举,以便您能够在检查器中查看它们。 字符串无法实现同样的功能。
以下是一些更新的源代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class Movement : MonoBehaviour
{
[Header("Movement Preferences")]
public int JumpHeight;
public int MoveSpeed;
[Header("Key Assignments")]
public KeyCode JumpButton;
public KeyCode MoveRightButton;
public KeyCode MoveLeftButton;
private Rigidbody2D rb;
// Start is called before the first frame update
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
private void Update()
{
if (Input.GetKeyDown(JumpButton))
rb.velocity = new Vector3(0, JumpHeight, 0);
if (Input.GetKey(MoveRightButton))
rb.velocity = new Vector3(MoveSpeed, 0, 0);
if (Input.GetKey(MoveLeftButton))
rb.velocity = new Vector3(MoveSpeed*-1, 0, 0);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.