I know that by the time you are doing this lecture, switch statements have not been explained but it is a really helpful trick to use instead of multiple if statements.
If you want to find out more about switches, here is an official Unity tutorial: Using switch statements
Here is my full code and it works flawlessly. (Sorry for anyone new to Unity)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hacker : MonoBehaviour {
int level;
enum Screen {MainMenu, Password, Win};
Screen currentScreen;
string playerInput;
// Use this for initialization
void Start () {
ShowMainMenu();
currentScreen = Screen.MainMenu;
}
void ShowMainMenu()
{
Terminal.ClearScreen();
Terminal.WriteLine("Hello Vlad? Ben? Bob??");
Terminal.WriteLine("Welcome to Terminal Hacker!");
Terminal.WriteLine("");
Terminal.WriteLine("Press 1 to hack the local Museum.");
Terminal.WriteLine("Press 2 to hack the Conference Center.");
Terminal.WriteLine("Press 3 to hack NASA's top secret base.");
Terminal.WriteLine("");
Terminal.WriteLine("Enter your selection:");
}
void OnUserInput (string input)
{
playerInput = input;
if (input == "menu")
{
ShowMainMenu();
currentScreen = Screen.MainMenu;
}
else if (currentScreen == Screen.MainMenu)
{
RunMainMenu(input);
}else if (currentScreen == Screen.Password)
{
switch (level)
{
case 1:
CheckPassword("donkey");
break;
case 2:
CheckPassword("new password");
break;
default:
break;
}
}
}
void CheckPassword(string password)
{
if (playerInput == password)
{
//Password is correct
Terminal.WriteLine("Password accepted. Well done!");
}
else
{
//Password incorrect
Terminal.WriteLine("Wrong Password. Try again.");
}
}
void RunMainMenu(string input)
{
if (input == "007")
{
Terminal.WriteLine("I've been waiting for you, Mr Bond *cough cough*");
}
else if (input == "1")
{
level = 1;
StartGame();
}
else if (input == "2")
{
level = 2;
StartGame();
}
else
{
Terminal.WriteLine("Please write a valid level");
}
}
void StartGame()
{
currentScreen = Screen.Password;
Terminal.WriteLine("You've chosen level " + level);
Terminal.WriteLine("Please Enter your password");
}
}
Edit: I extracted the input variable which we get from the handy function into a new variable called “playerInput”. Hope this helps.
Also, the code isn’t the cleanest possible and sorry if I’m jumping too far ahead of everyone. I will try not to do that but it is just how I would solve the problem.
Another edit: I continued to watch the course and literally 2 videos later it is talking about switches. Sorry @ben