Problems with my Cheatcode?

I was looking for some way to implement a cheat code into my game. The end result is desired to be that when the player enters “cjbruel”, the variable “scoreValue” in the script DestroyByContact is changed to 100. I got this script off of another UA question, and I’m not exactly sure how it works. For your viewing pleasure:

using UnityEngine;
using System.Collections;

public class CheatCodeListener : MonoBehaviour 
{
	private string[] cheatCode;
	private int index;

	void Start() 
	{
	    cheatCode = new string[] { "c", "j", "b", "r", "u", "e", "l"};
	    index = 0; 
	}
 
	void Update() 
	{
	    if (Input.anyKeyDown) 
		{
			if (Input.GetKeyDown(cheatCode[index])) 
			{
				index++;
       		}
			
			else 
			{
         		index = 0;   
       		}
    	}
 
    	if (index == cheatCode.Length) 
		{
			print("Cheatcode entered");
    	}
	}
}

It works, in the sense that when I play the game an enter “cjbruel”, The message “cheatcode entered” appears in the console, preceded by the “cheatcode entered” message a bazillion times… But the next button I press brings up this error :

IndexOutOfRangeException: Array index is out of range.
CheatCodeListener.Update () (at Assets/Scripts/CheatCodeListener.cs:19)

Now I guess this makes sense, since all of this is under Update. Basically, it works, but too well :slight_smile: I guess I should create another (I think we call them functions?)

void suchAndSuch () {}

I just don’t know how to work it. Lol I’m new if you couldn’t tell. Any help is appreciated!!!

Do this,

if (index == cheatCode.Length)
{
    print("Cheatcode entered");
    index = 0;
    suchAndSuch();
}

this will solve both of your problems, first the message will show only once, second since it will be put to 0 again after the next call in line 19 there will be no accessing cheatCode[index] where index is now for 1 bigger than it should be (indexes are decremented for 1, for example if we have length of 3, our last element is not at index 3 but instead, at index 2, because the first element starts from index 0 instead of index 1).

Inside of your suchAndSuch function, put everything that is related to what your cheat is supposed to do. Good luck!

Radivarig