Fresh deals just dropped! Jump into the Spring Sale and enjoy up to 45% off on Flash Deals.

Build a 2D Word Guessing Game in Unity (Step-by-Step Guide for Beginners)

Build a 2D Word Guessing Game in Unity (Step-by-Step Guide for Beginners)

Build a 2D Word Guessing Game in Unity (Step-by-Step Guide for Beginners)

How to Build a 2D Word Guessing Game in Unity

Let’s cut the chase. Building a 2D word guessing game in Unity requires the Game Canvas, GameManager, Letter Instantiator, Keyboard Input Listener, and Words Text File Reader. It’s a great project for beginners to learn Unity, but there is a lot of redundant code to write, along with a lot of alignment issues. The Unity 2D Game Templates offered on unitytemplate.com solve these issues and bottlenecks by offering prefab components, fully functional game input, and built game logic. This allows for faster game production and development.

At some point new developers tackle a puzzle game. As a game development foundation, the learning curve to game mechanics is small as the game rules are simple to understand. Beyond that, the game teaches developers to script in C#, manage and interact with the game UI, and handle user input.

This post details the process of how to make the game, and the actual C# code that was used, along with the bottlenecks during development that unity premium game templates solved, and how these templates accelerated development. By the end of this post you will know how to make the game, and when to use unity game codes and avoid the busywork.

What exactly is a guessing game?

Guessing games are simple. One word is randomly selected from a list and displayed with its letters hidden. Players then guess the letters one keypress at a time. They are shown the letters they guessed correctly the moment they get one right. Players get a finite number of guesses, which is tracked to maintain a score through the game.

Creating a version of this guessing game will teach you how to do the following in a computer program:

  • Read a word from a .txt file
  • Randomly select a word
  • Process and evaluate keystrokes
  • Show letters on a screen
  • Manage and show a score
  • Show a guess limit and know when a player has reached that limit

After you learn all of these, you will have a fully developed guessing game that has a playable game screen and Win and Lose screens.

[Insert Figure: Game flow diagram showing start screen → gameplay → win/lose screens]

What are the steps to create a word guessing game using Unity?

There are some preparatory steps before writing your first line of code. You will need to create a new 2D project using Unity (version 5.5 or more recent). The first of many code related tasks is removing the default background. Go to the Window header on the application, then go to Lighting. The Default Skybox should be removed, and your Game view should be empty.

Now, create a text component for the letter and add a canvas. In the inspector, set the position of the letter's Rect Transform to (0, 0, 0). Then, set the width and height to 100 and set the font size to 80. Set the text alignment to center in both the vertical and horizontal orientations. Next, create a prefab by dragging the letter object from the hierarchy to the project section.

Then, create an empty game manager object, and attach a C# script to it called GameManager. This will control the game and display the letters and manage the input for the game.

How do you write the GameManager script?

The GameManager script begins with a few important variables. The letter variable contains your prefab, cen is the center of the screen, and the rest are to track the word and the letters guessed:

public GameObject letter;
public GameObject cen;
private string wordToGuess = "";
private int lengthOfWordToGuess;
char[] lettersToGuess;
bool[] lettersGuessed;
 

The wordToGuess variable contains the word to be guessed. The lengthOfWordToGuess variable contains the length of the word, the lettersToGuess variable contains the array of the letters of the word, and the lettersGuessed variable contains the array of the status of the letters guessed by the player.

Drawing the Blanks with initLetters()

The initLetters() function goes through each character of the guessed word and creates a letter object for each character of the word. This next example with centering the guessed word is a bit more advanced. As you can see, it adds each letter object relative the center of the screen so that the full word is centered on the screen.

centering word example:

void initLetters() { 
   int nbletters = lengthOfWordToGuess; 
   for (int i = 0; i < nbletters; i++) { 
       Vector3 newPosition; 
       newPosition = new Vector3 (cen.transform.position.x + ((i-nbletters/2.0f) *100), 
           cen.transform.position.y, cen.transform.position.z); 
       GameObject l = (GameObject)Instantiate (letter, newPosition, Quaternion.identity); 
       l.name = "letter" + (i + 1); 
       l.transform.SetParent(GameObject.Find ("Canvas").transform); 
   } 
}

Things get a bit complicated, while centering the word, because letter positions are based off the game manager's position and not center of the screen. The centering process often requires several edits along this line, and can be based off the game manager, then based on the centerOfScreen object and then offset so that the full word is centered.

The next step is figuring out how to capture guesses.

Guessing a word can be as simple as pressing the keyboard letter A. This can be done with a single line of code: Input.GetKeyDown(KeyCode.A). However, capturing each letter of the alphabet is not simple because it would require 26 separate lines of code, one for each letter.

That's clearly an inefficient approach; a better option would be a checkKeyboard2() function. It sits above Input.anyKeyDown, captures the ASCII representation of a key pressed, and checks if it's in the range of the ASCII of lowercase letters (which is 97 to 122) like so:

void initLetters()


void checkKeyboard2()
{
   if (Input.anyKeyDown)
   {
       char letterPressed = Input.inputString.ToCharArray () [0];
       int letterPressedAsInt = System.Convert.ToInt32 (letterPressed);
       if (letterPressedAsInt >= 97 && letterPressed <= 122)
       {
           for (int i=0; i < lengthOfWordToGuess; i++)
           {
               if (!lettersGuessed [i])
               {
                   letterPressed = System.Char.ToUpper (letterPressed);
                   if (lettersToGuess [i] == letterPressed)
                   {
                       lettersGuessed [i] = true;
                       GameObject.Find("letter"+(i+1)).GetComponent().text = letterPressed.ToString();
                   }
               }
           }
       }
   }
}
It certainly is a superior solution, but it does create a different sort of challenge in your understanding of conversions and casting for characters. You will also need to replace the function in Update and comment out checkKeyboard() to place checkKeyboard2() in its place. This type of logic is the stuff you will find in quality unity game codes that are ready to go, that also have an input system that is fully functional right out of the box.

How do you read a list of words from a text file?

Manually entering a list of words into an array is tedious. Alternatively, we can read a list of words from a text file in the Resources folder in Unity. The method pickAWordFromFile() does exactly this: it reads the file, separates it into separate lines, and returns a random line of the file as a word.

string pickAWordFromFile()
{
   TextAsset t1 = (TextAsset)Resources.Load("words", typeof(TextAsset));
   string s = t1.text;
   string[] words = s.Split("\n"[0]);
   int randomWord = Random.Range(0, words.Length + 1);
   return words[randomWord];
}
 

What is the final product of this project?

Completing the project will teach you a number of skills, such as:

  • How to use UI and prefabs: You will learn how to create a UI, create letter prefabs, and change a Text object from a script.
  • How to use the Unity scripting API: You will learn how to handle keystrokes and how to generate random numbers.
  • How to manage the state of your game: You will learn how to use the PlayerPrefs class, how to control the score, and how create logic for win and lose scenarios in your game.

Since most Unity games use these concepts, this project is a good starting place to learn how to use Unity and 2D and 3D game code projects.

Where does development slow?

Despite its usefulness, the manual method has many time-wasting pitfalls for beginners, including:

Hardcoded arrays. The words are often hardcoded in the script (e.g. {"car", "elephant", "autocar"}) and scaling that to hundreds of words in a game becomes a drag until you implement file reading.

UI alignment problems. Centering the letters requires multiple code revisions and a firm understanding of Rect Transform coordinates and how those relate to the camera.

Function call order problems. The initGame() method needs to be called before the initLetters() method within the Start function, or the count of letters will not be set and the game will break.

UI Elements that overlap. When designing the lose screen, if a Text object and a button overlap, the button will not be clickable.

Actual developers face these problems. On the Unity forums, beginners building similar types of word games frequently have problems with the win condition being met too early, because the logic for revealing letters does not check each position. These problems are not unsolvable, but they are time that could be used to design the game and not debug.

What makes unitytemplate.com templates so fast?

The pre-built unity premium game templates are put to good use here. An example site is unitytemplate.com and has over 13,000 unity assets/codes, rated by over 85,000 patrons and has a forum of over 100,000 members, with each asset being moderated. In the puzzle section, one of the options is called Word Score – Complete Unity Game and costs around $35.

How does unity ready made game codes solve the bottlenecks?

Fastens UI setup

Templates come with a responsive layout, assets with styles built in, and animations are added. You skip all the trial-and-error in lining up letters and the multiple code edits that go with it.

State Management is Built In

Templates also come with a Modular Game Manager and all the scene changes are wired up. You also skip the 25 input-detection blocks and the surprises of how to order all the functions.

Visuals are Built In

Templates come with custom fonts and backgrounds as well as UI packs that are finished and not just blank and provide a great help for the step of presenting a game.

Prefabs come with a built In Input System

Prefabs come with a built in and ready to go Keyboard and Buttons. This avoids a lot of the win-too-early bugs that so many beginners face.

Manual setup vs UnityTemplate.com: A comparison

FeatureManual SetupUnityTemplate.com
UI ConfigurationManual Canvas and Rect Transform tuning followed by multiple adjustments and alignment codingLayouts are already built and responsive
Input TrackingCode custom ASCII filtering and debugInput detection already built and functioning
Data ManagementSet a custom file in the Resources folder or hardcode an arrayCustom word lists and editors built in; often no coding necessary
Time to PrototypeDays to weeks, based on your experienceHours

Who are templates for?

  • Beginners hoping to have a fully functional game to learn and modify, instead of having nothing and starting from scratch.
  • Indie developers hoping to quickly publish games and invest the rest of their time on design and marketing.
  • Fast prototypes for game jams that are time constrained

If you have no experience and want to learn the fundamentals of C# and Unity, the best way to learn this is by hand building the game. If you want to ship a game that is polished and playable, then the Unity premium game templates are the best option. These are also good references if you want to learn more game coding and development while game building.

Ready to code a puzzle game?

There is definitely a benefit to coding a guessing game from scratch. The skills that you learn from this, like UI updates, input detection, and file updates, are skills that you will definitely use in every other Unity project that you work on.

No one expects you to start from scratch on every project. To get started, check out the Unity 2D game templates at unitytemplate.com. You can pick up fully completed, Unity-approved projects like Word Score – Complete Unity Game. You can purchase word puzzle codes, or buy unity game codes for 3D projects. Templates like these save you repeated effort on the boring parts of game development, help you avoid common problems, and let you jump straight to implementing your unique ideas. Templates can be opened and modified.

Common Questions:

What tools do I need to make a word guessing game?

You need a version of Unity greater than or equal to 5.5 with 2D selected, and a basic understanding of C#. Though each step is basic, it is more approachable with an understanding of the software and the coding language.

What is the advantage of using Input.anyKeyDown over Input.GetKeyDown?

Using Input.GetKeyDown would require you to duplicate a code block over 26 times. Input.anyKeyDown is more compact, and coupled with the key code to int conversion and a check to see if the int falls between 97 and 122, gives a more efficient, and easy to maintain, code block.

How can you access a word list stored within a file in Unity?

To access a word list, place a text file in the Resources folder in the Unity project. Each line will be a single word, and this file can be accessed with Resources.Load("words", typeof(TextAsset)). To get an array of words you can split the text on the newline and even pick one at random. The file can be replaced to easily switch the word list to another language.

What are Unity game templates and game codes priced at?

On unitytemplate.com, the cost of the Word Score - Complete Unity Game template is approximately $35. From the puzzle catalog, unity assets and codes are typically priced between $29 and $99, and extended licenses are available at a cost.

Is it wrong to purchase unity game codes rather than coding a game from scratch?

Absolutely not. In the professional game development industry, employing templates and pre-designed game codes is highly common. It is a quick and efficient way to publish a game and to use a project to learn from. However, for those learning, coding a game from the very start is the best way to learn.

Will using a Game Template in Unity prevent me from learning the software?

No. It is very possible to advance your learning by using complete templates to see how professional developers of the game use structures to create their scripts, prefabs, and different forms of input. Many developers learn best by altering pre-existing projects.