I fancied researching a slightly different approach to how the greeting presents itself in this lecture. I’m a C# novice but generally familiar with development concepts.
Instead of hard-coding the name inside the greeting, I wanted to see if I could pull the current logged in username from the computer being used.
And it was incredibly easy so thought I would share it.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hacker : MonoBehaviour
{
void Start()
{
string greeting = "Welcome " + Environment.UserName + "!";
ShowMainMenu(greeting);
}
void ShowMainMenu(string greeting)
{
Terminal.WriteLine(greeting);
Terminal.WriteLine("");
Terminal.WriteLine("What would you like to hack into?");
Terminal.WriteLine("");
Terminal.WriteLine("1) Your local library (easy)");
Terminal.WriteLine("2) Your work computer (medium)");
Terminal.WriteLine("3) GCHQ (hard)");
Terminal.WriteLine("");
Terminal.WriteLine("Enter your selection:");
}
void Update()
{
}
}
This should already be fairly similar to your code at the end of this lecture but with a small change.
Instead of a greeting
variable that looks like:
string greeting = "Welcome Chris!";
We want to pass in the real username of the user playing the game.
To get that we can get the value of the UserName
property which is stored in the System.Environment
class which should be available on Windows or macOS. That is done simply like this:
System.Environment.UserName
We also need to be familiar with the concept of string concatenation (which will be covered later, I’m sure). Much like many programming languages, this simply involves joining together two or more strings using a concatenation operator which in C# is simply the +
character.
So if we still wanted to hard-code the name into the greeting we could do this with multiple string parts:
string greeting = "Welcome " + "Chris" + "!";
Which produces the same variable value as:
string greeting = "Welcome Chris!";
So now we know how to concatenate strings, we can replace "Chris"
there with the previously mentioned username property:
string greeting = "Welcome " + System.Environment.UserName + "!";
In doing that, running the code should produce something like this:
The code is fairly naive and doesn’t handle things like the username being empty or containing weird characters or being too long and such issues, but thought it was pretty cool and worth sharing