![](/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.