Reputation: 21
Im currently trying to make a basic clicker game to start to teach myself how to do C# and i've been able to resolve most problems with this part but not yet. Right not I'm programming a buyable upgrade that generates money on it's own which I think I got down but theres an error with one of the if statements and I don't know to fix it. Does anyone else know what I did wrong?
Code:
private int a = 0;
private void flatButton1_Click(object sender, EventArgs e)
{
a++;
flatTextBox1.Text = a.ToString($"Knowledge: {a}");
}
private void flatButton2_Click(object sender, EventArgs e)
{
if (a >= 50)
{
bool upgrade1 = true;
}
if (upgrade1 == true)
{
for ( ; ; )
{
a = a + (a++ * 2);
}
}
The only thing that is giving an error is the if(upgrade1 = true), the upgrade1 is the error, it says that The name 'upgrade1' does not exist in the current context.
Upvotes: 2
Views: 1618
Reputation: 52
You have declared variable "upgrade1" in the scope of 1st IF statement so it can only be used in that IF statement. You need to declare "upgrade1" variable globally. (outside of IF statement
private int a = 0;
private void flatButton1_Click(object sender, EventArgs e)
{
a++;
flatTextBox1.Text = a.ToString($"Knowledge: {a}");
}
private void flatButton2_Click(object sender, EventArgs e)
{
bool upgrade1 =false;
if (a >= 50)
{
upgrade1 = true;
}
if (upgrade1 == true)
{
for ( ; ; )
{
a = a + (a++ * 2);
}
}
Upvotes: 2
Reputation: 247
That is because you defined upgrade1 in your first if statement, so your second can't reach it.
Change your code to this:
private int a = 0;
private void flatButton1_Click(object sender, EventArgs e)
{
a++;
flatTextBox1.Text = a.ToString($"Knowledge: {a}");
}
private void flatButton2_Click(object sender, EventArgs e)
{
bool upgrade1;
if (a >= 50)
{
upgrade1 = true;
}
if (upgrade1 == true)
{
for ( ; ; )
{
a = a + (a++ * 2);
}
}
}
Upvotes: 1
Reputation: 21
You have to remember about scopes when writing code. The reason your code isn't working is because the if statement check to see if upgrade1 is true has no idea that the variable upgrade1 even exists. You have to move the variable definition out one scope so the if statement check knows what you are talking about. Hope this helps!
This should fix your issue:
private void flatButton2_Click(object sender, EventArgs e)
{
bool upgrade1;
if (a >= 50)
{
upgrade1 = true;
}
else
{
upgrade1 = false;
}
if (upgrade1 == true)
{
for ( ; ; )
{
a = a + (a++ * 2);
}
}
}
Upvotes: 1