Defining variable in Start() [SOLVED]

I firstly tried to define the string in the Start() function, before calling it in the ShowMainMenu() function but it produced an error and wouldn’t run.

What isn’t this possible? Surely if my program uses a variable it will be available to all functions or is this not the case? It clearly doesn’t work with these simple statements, is there a way to make it global?

I hope that makes sense, I’m not really sure about the terminology :confused:

// Use this for initialization
void Start () {
    string greeting = "Hello Gary";
    ShowMainMenu();
}

void ShowMainMenu () {
    NewLine();
    Terminal.ClearScreen();
    Terminal.WriteLine(greeting);
    NewLine();
    Terminal.WriteLine("  **********************************  ");
    Terminal.WriteLine("  *    Choose a target to hack     *  ");
    Terminal.WriteLine("  **********************************  ");
    NewLine();
    Terminal.WriteLine("Press 1 for LIBRARY");
    Terminal.WriteLine("Press 2 for POLICE STATION");
    Terminal.WriteLine("Press 3 for NASA");
    NewLine();
    Terminal.WriteLine("Enter your selection:");
}

void NewLine () {
    Terminal.WriteLine("");
}

Ok, I took a break and thought about it more logically. I think it works like this…
Variables are limited to the function in which they reside.
By putting the variable outside of the function, on the next level up, in the class Hacker, then it will be available to all the functions within that class.

So I reformatted my code and now it works as intended.

public class Hacker : MonoBehaviour {
string greeting = "Hello Gary";
// Use this for initialization
void Start () {
    ShowMainMenu();
}

void ShowMainMenu () {
    NewLine();
    Terminal.ClearScreen();
    Terminal.WriteLine(greeting);
    NewLine();
    Terminal.WriteLine("  **********************************  ");
    Terminal.WriteLine("  *    Choose a target to hack     *  ");
    Terminal.WriteLine("  **********************************  ");
    NewLine();
    Terminal.WriteLine("Press 1 for LIBRARY");
    Terminal.WriteLine("Press 2 for POLICE STATION");
    Terminal.WriteLine("Press 3 for NASA");
    NewLine();
    Terminal.WriteLine("Enter your selection:");
}

void NewLine () {
    Terminal.WriteLine("");
}
2 Likes

Privacy & Terms