I would like to implement Doom-style cheat codes. That is when the user types in a given succession of letters, something should happen in my game. How would I go about implementing that?
2 Answers
2Its actually pretty straight forward. What you need to consider is the delay before the currently typed in string is cleared, which codes you'll accept and possibly a target GameObject - if you plan on handling the accepted codes somewhere else.
The code below shows a simple implementation. Try saving it out as CheatCodeListener.cs, adding it to a GameObject and populating the codes list with "Test".
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CheatCodeListener : MonoBehaviour
{
private string m_Keys = "";
private float m_LastKeyTime;
public List <string> m_Codes = new List <string> ();
public float m_ClearDelay = 2.0f;
public GameObject m_Receiver = null;
void Start ()
{
m_LastKeyTime = Time.time
for (int i = 0; i < m_Codes.Count; i++)
{
m_Codes <em>= m_Codes *.ToLower ();*</em>
_*}*_
_*}*_
_*void Update ()*_
_*{*_
_*if (Input.anyKey)*_
_*{*_
<em>*m_LastKeyTime = Time.time;*</em>
_*}*_
<em>*else if (Time.time - m_LastKeyTime > m_ClearDelay)*</em>
_*{*_
<em>*m_Keys = "";*</em>
_*}*_
<em>*m_Keys += Input.inputString.ToLower ();*</em>
<em>*if (m_Codes.Contains (m_Keys))*</em>
_*{*_
<em>*string message = "On" + char.ToUpper (m_Keys [0]) + m_Keys.Substring (1) + "Code";*</em>
<em>*if (m_Receiver == null)*</em>
_*{*_
_*SendMessage (message);*_
_*}*_
_*else*_
_*{*_
<em>*m_Receiver.SendMessage (message);*</em>
_*}*_
<em>*m_Keys = "";*</em>
_*}*_
_*}*_
_*void OnTestCode ()*_
_*// Handle codes in scripts on the target GameObject (or the current one if*_
_*// no target is set) by implementing functions named On{Name}Code - note*_
_*// that the codes are set to be all-lowercase except for the first letter.*_
_*{*_
_*Debug.Log ("We caught a code!");*_
_*}*_
_*}*_
_*```*_
Here : unitynoobs you can download a small project with this answer!
Interesting, useful to centralize a set of hotkeys also!
– davebuchhoferNice script, possible applications in validation fields
– anon42580617Does it work in Unity 3.X? I did what you said, but I get this error: > ArgumentException: get_time can only > be called from the main thread. > Constructors and field initializers > will be executed from the loading > thread when loading a scene. Don't use > this function in the constructor or > field initializers, instead move > initialization code to the Awake or > Start function. > CheatCodeListener..ctor ()
– Al-AnselmoIt wasn't. Now it is.
– AngryAntDo you have a Javascript version?
– theorbitgames