Friday, May 12, 2017

Keyboard based Debugger for Unity3D Projects

There is nothing complex here but I've found the following code extremely useful to quickly test functionality without having to mock up buttons. All you have to do is add this component to a GameObject then select Keycodes that you would like to pair with functions. You can also flag whether you want this to only occur in the editor or if you want to leave it for live production.

I'd like to get in the habit of posting more code. I tend to avoid it as anything interesting to me is usually overly complex or client specific. That said, if you found this snippet helpful I'd love to hear from you and I'll keep posting bite sized components that I find useful.

Example of the component:


Code:
 public class KeyboardCommandManager : MonoBehaviour
    {
        [System.Serializable]
        public struct KeyAndResponse
        {
            public KeyCode Key;
            public UnityEvent Response;
            public bool EditorOnly;
        }

        public KeyAndResponse[] KeysAndResponses;
        private List<KeyAndResponse> ActiveKeys;

        private void Awake()
        {
            ActiveKeys = new List<KeyAndResponse>();
            if(KeysAndResponses!=null)
            {
                for (int i = 0; i < KeysAndResponses.Length; i++)
                {
                    var keyAndResponse = KeysAndResponses[i];
                    if(!keyAndResponse.EditorOnly || Application.isEditor)
                    {
                        ActiveKeys.Add(keyAndResponse);
                    }
                }
            }
        }
 
        void Update()
        {
            if (Input.anyKeyDown)
            {
                 
                    for (int i = 0; i < ActiveKeys.Count; i++)
                    {
                        var keyAndResponse = ActiveKeys[i];

                        if(Input.GetKeyDown(keyAndResponse.Key))
                            keyAndResponse.Response.Invoke();
                    }
                 
            }
        }
    }

No comments: