Unity C #: Caching keyboard / controller state?

I was just starting out with unity, so please excuse my lack of knowledge. I started programming with microsoft xna environment. Now I have switched to unity, but I have problems. Xna had a KeyboardState function that checked which buttons / keys were pressed. I heard that Unity doesn't have the same feature, so I was wondering how I can store / cache the data for the last 15 frames. I heard that Event.KeyboardEvent and KeyCode can help, but I am lost. Can anyone please help?

+3


source to share


2 answers


Do you want to store or cache input for 15 frames? I can tell you how to collect input, you can cache it from there if you like, storing it in a global array Keycode[]

.

This code will print the pressed key on the console.



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

      

+1


source


You can iterate over all possible codepoints and save their meaning for future use:



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);
        }
    }

}

      

0


source







All Articles