[Solved] A way to simplify the program?

Hi,
I’ve been messing around with the TextController, and I’ve come up with a simple text editor where you can type numbers and spaces. I wondered that my program basically contains a lot of repeated code, but I don’t see a way to simplify it! This is my Update() method:

void Update () {
		if (Input.GetKeyDown (KeyCode.Space)) {
			text.text += " ";
		} if (Input.GetKeyDown (KeyCode.Alpha1)) {
			text.text += "1";
		} if (Input.GetKeyDown (KeyCode.Alpha2)) {
			text.text += "2";
		} if (Input.GetKeyDown (KeyCode.Alpha3)) {
			text.text += "3";
		} if (Input.GetKeyDown (KeyCode.Alpha4)) {
			text.text += "4";
		} if (Input.GetKeyDown (KeyCode.Alpha5)) {
			text.text += "5";
		} if (Input.GetKeyDown (KeyCode.Alpha6)) {
			text.text += "6";
		} if (Input.GetKeyDown (KeyCode.Alpha7)) {
			text.text += "7";
		} if (Input.GetKeyDown (KeyCode.Alpha8)) {
			text.text += "8";
		} if (Input.GetKeyDown (KeyCode.Alpha9)) {
			text.text += "9";
		} if (Input.GetKeyDown (KeyCode.Alpha0)) {
			text.text += "0";
		}

I would appreciate any input to simplify this piece of code, it doesn’t affect the speed of the program much, but just for organizing and learning reasons ;).

Thanks in advance!!!

1 Like

You can use arrays like this:

public KeyCode[] key;
public string[] numbers;


void Update()
{
	Inputs();
}


void Inputs()
{
	for (int i = 0 ; i < numbers.Length ; i++)
	{
		if (Input.GetKeyDown(key[i]))
		{
			text.text += numbers[i];
		}
	}
}

This should work, you would need to choose the values in the inspector, just make sure that the both numbers[] and key[] have the same size

Arrays are your friends =)
Let me know if you made it work

1 Like

Thanks a lot for your quick response, I’m on my iPad right now, so I can’t test the code at the moment, although it seems as though it works fine! I do have a question though: In the first line you’ve declared the array to be of type KeyCode, so is it necessary to still refer to KeyCode in the list (eg. Keycode.Space, KeyCode.Alpha1, etc.), or does the compiler interpret the items in the list as KeyCodes automatically?
Furthermore, I appreciate the habit of letting your Update() method as clear as possible, that’s a lot more organized in large games!

1 Like

The inspector will give you an drop-down menu with the options to choose which keycode do you want to use :slight_smile:

Yes, it can get very confusing when we put everything straight inside the update(), I use a option inside the monodevelop that allows us to collapse the methods (pressing a small “-” symbol) and make the visualization easier across the script. Keeping the raw code outside the update helps organizing it too.

1 Like

Privacy & Terms