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

3 comments:

SolvedApp said...

Uff saved me a bunch of minutes, thanks man!

yanmaneee said...

supreme outlet
golden goose mid star
supreme clothing
yeezy 700
curry shoes
yeezy outlet
paul george shoes
supreme shirt
moncler
goyard

seep learn said...

Unity Debug Class: Unity provides the Debug class which includes methods like Log, LogWarning, and LogError for basic logging. While this is essential, a more structured approach involves custom debugging tools.

IEEE projects for cse

Custom Debugging Scripts: Create custom scripts in your Unity project to handle debugging functionalities.

python projects for final year students