Unity C#:缓存键盘/控制器状态



我刚刚开始统一,所以请原谅缺乏知识。我开始使用微软的xna环境进行编程。我现在已经转向团结,但我遇到了麻烦。Xna有一个"键盘状态"功能,可以检查正在按下的按钮/键。我听说 Unity 没有相同的功能,所以我想知道如何存储/缓存过去 15 帧的输入。我听说Event.KeyboardEvent和KeyCode可能会有所帮助,但我迷路了。任何人都可以帮忙吗???

您想存储或缓存 15 帧的输入吗?我可以告诉你如何收集输入,如果你愿意,你可以从那里缓存它,把它存储在一个全局Keycode[]数组中。

此代码会将按下的键打印到您的控制台。

void OnGUI() {
    Event e = Event.current;
    if (e.isKey){
        string key = e.keyCode.ToString();
        Debug.Log(key);
    }
}

您可以遍历所有可能的键码,并存储其值以备将来使用:

using UnityEngine;
using System.Collections.Generic;
public class KeyboardState : MonoBehaviour {
    /// <summary>
    /// Keyboard input history, lower indexes are newer
    /// </summary>
    public List<HashSet<KeyCode>> history=new List<HashSet<KeyCode>>();

    /// <summary>
    /// How much history to keep?
    /// history.Count will be max. this value
    /// </summary>
    [Range(1,1000)]
    public int historyLengthInFrames=10;

    void Update() {
        var keysThisFrame=new HashSet<KeyCode>();
        if(Input.anyKeyDown)
            foreach(KeyCode kc in System.Enum.GetValues(typeof(KeyCode)))
                if(Input.GetKey(kc))
                    keysThisFrame.Add(kc);
        history.Insert(0, keysThisFrame);
        int count=history.Count-historyLengthInFrames;
        if(count > 0)
            history.RemoveRange(historyLengthInFrames, count);
    }

    /// <summary>
    /// For debug Purposes
    /// </summary>
    void OnGUI() {
        for(int ago=history.Count-1; ago >= 0; ago--) {
            var s=string.Format("{0:0000}:", ago);
            foreach(var k in history[ago])
                s+="t"+k;
            GUILayout.Label(s);
        }
    }
}

最新更新