2.4 - Console Input and Output
Console input and output operations allow your program to interact with users by reading input and displaying information. While Unity games typically use graphical interfaces rather than console interaction, understanding these concepts is essential for learning C# and creating simple test programs.
Console Output
The Console
class in the System
namespace provides methods for outputting text to the console window.
Basic Output with Console.WriteLine()
The most common method for console output is WriteLine()
, which displays a line of text and moves to the next line:
Console.WriteLine("Welcome to the Adventure Game!");
Console.WriteLine("Your journey begins now...");
Output:
Welcome to the Adventure Game!
Your journey begins now...
Output Without Line Break: Console.Write()
If you don't want to move to a new line after displaying text, use the Write()
method:
Console.Write("Enter your name: ");
// Cursor stays on the same line, ready for user input
Output:
Enter your name: _
Displaying Variable Values
You can display variable values by including them in your output:
int playerLevel = 5;
int playerHealth = 100;
string playerName = "Adventurer";
Console.WriteLine("Player: " + playerName);
Console.WriteLine("Level: " + playerLevel);
Console.WriteLine("Health: " + playerHealth);
Output:
Player: Adventurer
Level: 5
Health: 100
String Concatenation
In the example above, we used the +
operator to combine (concatenate) strings and variable values. This is called string concatenation:
string weapon = "Sword";
int damage = 15;
// String concatenation with the + operator
string message = "You attack with your " + weapon + " for " + damage + " damage!";
Console.WriteLine(message);
Output:
You attack with your Sword for 15 damage!
While string concatenation works, it can become unwieldy for complex strings with many variables.
String Interpolation (C# 6+)
C# 6.0 introduced string interpolation, which provides a more readable way to include variable values in strings. Prefix the string with $
and include variables in curly braces {}
:
string weapon = "Sword";
int damage = 15;
// String interpolation with $"..." syntax
string message = $"You attack with your {weapon} for {damage} damage!";
Console.WriteLine(message);
Output:
You attack with your Sword for 15 damage!
Expressions in String Interpolation
You can include expressions, not just variables, within the curly braces:
int baseAttack = 10;
int strengthBonus = 5;
Console.WriteLine($"Total attack power: {baseAttack + strengthBonus}");
Console.WriteLine($"Critical hit damage: {(baseAttack + strengthBonus) * 2}");
Output:
Total attack power: 15
Critical hit damage: 30
Formatting in String Interpolation
You can specify formatting inside the interpolation braces using a colon :
followed by a format specifier:
double hitChance = 0.75;
decimal goldAmount = 1234.56m;
DateTime gameStartTime = DateTime.Now;
// Formatting numbers and dates
Console.WriteLine($"Hit chance: {hitChance:P0}"); // Percentage with 0 decimal places
Console.WriteLine($"Gold: {goldAmount:C2}"); // Currency with 2 decimal places
Console.WriteLine($"Game started at: {gameStartTime:t}"); // Short time format
Output (may vary based on your system's regional settings):
Hit chance: 75%
Gold: $1,234.56
Game started at: 10:30 AM
Common format specifiers include:
N
- Number with thousand separators (e.g.,{value:N2}
for 2 decimal places)P
- Percentage (e.g.,{value:P0}
for 0 decimal places)C
- Currency (e.g.,{value:C2}
for 2 decimal places)F
- Fixed-point (e.g.,{value:F1}
for 1 decimal place)D
- Decimal (integer) with specified minimum digits (e.g.,{value:D4}
for at least 4 digits)
String Formatting with string.Format()
Before string interpolation, the primary method for formatting strings was string.Format()
. It's still useful in some scenarios:
string playerName = "Elena";
int playerLevel = 7;
float playerHealth = 85.5f;
// Using string.Format()
string status = string.Format("Player: {0}, Level: {1}, Health: {2:F1}",
playerName, playerLevel, playerHealth);
Console.WriteLine(status);
Output:
Player: Elena, Level: 7, Health: 85.5
In string.Format()
, the placeholders {0}
, {1}
, etc. refer to the arguments that follow the format string, in order.
Console Input
To read input from users, use the Console.ReadLine()
method, which reads a line of text entered by the user:
Console.Write("Enter your character name: ");
string characterName = Console.ReadLine();
Console.WriteLine($"Welcome, {characterName}! Your adventure awaits.");
Reading and Converting Numeric Input
ReadLine()
always returns a string, so you need to convert it to the appropriate type for numeric input:
Console.Write("Enter your character's age: ");
string ageInput = Console.ReadLine();
// Convert string to integer
if (int.TryParse(ageInput, out int age))
{
Console.WriteLine($"Your character is {age} years old.");
}
else
{
Console.WriteLine("Invalid age input.");
}
Reading a Single Key with Console.ReadKey()
To read a single keypress without requiring the user to press Enter, use ReadKey()
:
Console.WriteLine("Press any key to continue...");
ConsoleKeyInfo keyInfo = Console.ReadKey();
Console.WriteLine($"\nYou pressed: {keyInfo.KeyChar}");
// For direction controls
Console.WriteLine("Use W, A, S, D to move (press Q to quit)");
bool quit = false;
while (!quit)
{
ConsoleKeyInfo key = Console.ReadKey(true); // true means don't display the key
switch (key.Key)
{
case ConsoleKey.W:
Console.WriteLine("Moving up");
break;
case ConsoleKey.A:
Console.WriteLine("Moving left");
break;
case ConsoleKey.S:
Console.WriteLine("Moving down");
break;
case ConsoleKey.D:
Console.WriteLine("Moving right");
break;
case ConsoleKey.Q:
Console.WriteLine("Quitting");
quit = true;
break;
}
}
Formatting Console Output
Changing Text Color
You can change the color of console text for emphasis or to create a better user interface:
// Display error message in red
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Error: Invalid command!");
// Display success message in green
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Success! Level completed.");
// Reset to default color
Console.ResetColor();
Console.WriteLine("Normal text continues here.");
Creating Simple UI Elements
You can create simple UI elements like progress bars or menus:
// Simple health bar
int health = 70; // 70% health
Console.Write("Health: [");
for (int i = 0; i < 10; i++)
{
if (i < health / 10)
Console.Write("█");
else
Console.Write(" ");
}
Console.WriteLine("] " + health + "%");
// Simple menu
Console.WriteLine("=== GAME MENU ===");
Console.WriteLine("1. New Game");
Console.WriteLine("2. Load Game");
Console.WriteLine("3. Options");
Console.WriteLine("4. Quit");
Console.Write("Select an option: ");
Output:
Health: [███████ ] 70%
=== GAME MENU ===
1. New Game
2. Load Game
3. Options
4. Quit
Select an option: _
Practical Examples
Example 1: Character Creation
Console.WriteLine("=== CHARACTER CREATION ===");
// Get character name
Console.Write("Enter character name: ");
string name = Console.ReadLine();
// Get character class
Console.WriteLine("\nChoose a class:");
Console.WriteLine("1. Warrior");
Console.WriteLine("2. Mage");
Console.WriteLine("3. Rogue");
Console.Write("Enter your choice (1-3): ");
string classChoice = Console.ReadLine();
string characterClass;
switch (classChoice)
{
case "1":
characterClass = "Warrior";
break;
case "2":
characterClass = "Mage";
break;
case "3":
characterClass = "Rogue";
break;
default:
characterClass = "Adventurer";
Console.WriteLine("Invalid choice. Defaulting to Adventurer.");
break;
}
// Generate random starting stats
Random random = new Random();
int strength = characterClass == "Warrior" ? random.Next(5, 11) : random.Next(3, 8);
int intelligence = characterClass == "Mage" ? random.Next(5, 11) : random.Next(3, 8);
int agility = characterClass == "Rogue" ? random.Next(5, 11) : random.Next(3, 8);
int health = 80 + strength * 5;
int mana = 50 + intelligence * 5;
// Display character sheet
Console.WriteLine("\n=== CHARACTER SHEET ===");
Console.WriteLine($"Name: {name}");
Console.WriteLine($"Class: {characterClass}");
Console.WriteLine($"Health: {health}");
Console.WriteLine($"Mana: {mana}");
Console.WriteLine($"Strength: {strength}");
Console.WriteLine($"Intelligence: {intelligence}");
Console.WriteLine($"Agility: {agility}");
Console.WriteLine("\nPress any key to begin your adventure...");
Console.ReadKey();
Example 2: Simple Text-Based Game Loop
int playerHealth = 100;
int playerGold = 50;
int monstersDefeated = 0;
bool gameRunning = true;
Console.WriteLine("=== DUNGEON ADVENTURE ===");
Console.WriteLine("Type 'help' for a list of commands.");
while (gameRunning && playerHealth > 0)
{
Console.Write("\n> ");
string command = Console.ReadLine().ToLower();
switch (command)
{
case "help":
Console.WriteLine("Available commands:");
Console.WriteLine(" status - Check your current stats");
Console.WriteLine(" explore - Explore the dungeon");
Console.WriteLine(" rest - Restore some health (costs 10 gold)");
Console.WriteLine(" quit - Exit the game");
break;
case "status":
Console.WriteLine($"Health: {playerHealth}/100");
Console.WriteLine($"Gold: {playerGold}");
Console.WriteLine($"Monsters defeated: {monstersDefeated}");
break;
case "explore":
Console.WriteLine("You venture deeper into the dungeon...");
// Random encounter
Random random = new Random();
int encounter = random.Next(1, 4);
if (encounter == 1)
{
// Found gold
int goldFound = random.Next(5, 16);
playerGold += goldFound;
Console.WriteLine($"You found {goldFound} gold!");
}
else if (encounter == 2)
{
// Monster battle
Console.WriteLine("You encounter a monster!");
int damage = random.Next(5, 21);
playerHealth -= damage;
Console.WriteLine($"After a tough battle, you defeat the monster but take {damage} damage.");
monstersDefeated++;
// Random gold reward
int goldReward = random.Next(10, 21);
playerGold += goldReward;
Console.WriteLine($"You loot {goldReward} gold from the monster.");
}
else
{
// Nothing happens
Console.WriteLine("You find nothing of interest.");
}
break;
case "rest":
if (playerGold >= 10)
{
playerGold -= 10;
int healthRestored = 20;
playerHealth = Math.Min(100, playerHealth + healthRestored);
Console.WriteLine($"You rest at a safe spot. Health restored to {playerHealth}. (-10 gold)");
}
else
{
Console.WriteLine("You don't have enough gold to rest.");
}
break;
case "quit":
Console.WriteLine("Thanks for playing!");
gameRunning = false;
break;
default:
Console.WriteLine("Unknown command. Type 'help' for a list of commands.");
break;
}
// Check if player died
if (playerHealth <= 0)
{
Console.WriteLine("\nYou have been defeated! Game over.");
Console.WriteLine($"Final score: {monstersDefeated} monsters defeated, {playerGold} gold collected.");
}
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
Console I/O vs. Unity's Debug and UI Systems
While console I/O is useful for learning C# and creating simple test programs, Unity games typically use different approaches for input and output:
Input in Unity
- User input is handled through the
Input
class or the newer Input System - Players interact through keyboard, mouse, touch, controllers, etc.
- UI elements like buttons and input fields handle user interaction
Output in Unity
- Visual output is displayed through the game's graphics and UI
- Text is shown using UI Text or TextMeshPro components
- Debug information is logged using
Debug.Log()
,Debug.LogWarning()
, andDebug.LogError()
In Unity development, you'll rarely use Console.WriteLine()
or Console.ReadLine()
. Instead:
- Use
Debug.Log()
to output debug information to the Unity Console window - Use UI elements like Text, Button, and InputField for user interaction
- Use Unity's Input system to handle keyboard, mouse, and controller input
However, the string formatting techniques you've learned (especially string interpolation) are directly applicable to Unity when formatting text for UI elements or debug messages.
Conclusion
Console input and output operations are fundamental to learning C# programming. They allow you to interact with users, display information, and create simple text-based applications. While Unity games use different mechanisms for input and output, the concepts and string formatting techniques you've learned are transferable to Unity development.
In the next section, we'll explore nullable value types and nullable reference types, which provide ways to represent the absence of a value in your C# programs.
Try creating a simple text-based game or utility using console I/O. This could be a calculator, a quiz game, a text adventure, or any other program that takes user input and produces output based on that input. This practice will help reinforce your understanding of variables, operators, type conversion, and console I/O.