- Home /
How could I implement cheat codes in my game?
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?
Answer by AngryAnt · Dec 21, 2009 at 05:12 PM
Its 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 [i] = m_Codes [i].ToLower ();
}
}
void Update ()
{
if (Input.anyKey)
{
m_LastKeyTime = Time.time;
}
else if (Time.time - m_LastKeyTime > m_ClearDelay)
{
m_Keys = "";
}
m_Keys += Input.inputString.ToLower ();
if (m_Codes.Contains (m_Keys))
{
string message = "On" + char.ToUpper (m_Keys [0]) + m_Keys.Substring (1) + "Code";
if (m_Receiver == null)
{
SendMessage (message);
}
else
{
m_Receiver.SendMessage (message);
}
m_Keys = "";
}
}
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!");
}
}
Interesting, useful to centralize a set of hotkeys also!
Nice script, possible applications in validation fields
Does 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, ins$$anonymous$$d move initialization code to the Awake or Start function. CheatCodeListener..ctor ()
Answer by $$anonymous$$ · May 01, 2012 at 04:58 PM
Here : unitynoobs you can download a small project with this answer!
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Update - Delaying until next frame? 0 Answers
Mecanim character wobbles when changing camera relative direction. 0 Answers
how to integrate steering wheel controller for ps3 in unity?? 0 Answers
how to use gui buttons as input get axis for mobile? 1 Answer