Unity3D Code repeats too much - c#

I am trying to make if you got enough gold then comes you need rock, if you got enough rock then you need enough gold, but if you have both then you can "Upgrade". But if you got both then it goes back to the you need gold.
void Update()
{
if(enoughgold == true & enoughrocks == true)
{
Upgrade.text = "Upgrade to 2014!";
}
if(sellrocks.gold > 9999)
{
enoughgold = true;
}
else
{
enoughgold = false;
}
if(click.rock > 2999)
{
enoughrocks = true;
}
else
{
enoughrocks = false;
}
if(enoughgold == true)
{
Upgrade.text = "You need 3,000 Rocks!";
}
else
{
Upgrade.text = "You need 10,000 Gold!";
}
if (enoughrocks == true)
{
Upgrade.text = "You need 10,000 Gold!";
}
else
{
Upgrade.text = "You need 3,000 Rocks!";
}
}

How about something like this? You first see whether the user has enough gold and rocks and then do the checking.
I have simplified if (enoughgold == true) to if (enoughgold) as the == true is redundant.
void Update()
{
enoughgold = sellrocks.gold > 9999;
enoughrocks = click.rock > 2999;
if (enoughgold && enoughrocks)
Upgrade.text = "Upgrade to 2014!";
else if (enoughgold && !enoughrocks)
Upgrade.text = "You need 3,000 Rocks!";
else if (!enoughgold && enoughrocks)
Upgrade.text = "You need 10,000 Gold!";
else if (!enoughgold && !enoughrocks)
Upgrade.text = "You need 10,000 Gold and 3,000 Rocks!";
}
You could also create an enum to handle all 4 possibilities: if the user has only enough rocks, if the user has only enough gold, if the user has enough of both and if the user doesn't have enough of any.

Related

Issue with Unity Update Loop

I was playing a little in Unity on a project and I stumbled upon an issue I can't address. Please keep in mind I am a beginner, and my understanding of Unity is fairly limited.
So the issue is this..
I wanted to test some if statement that went like this:
void Update()
{
if (isRow1Good() || isRow2Good() || isRow3Good() || isRow4Good() || isRow5Good() ||
isRow6Good() || isRow7Good() || isRow8Good() || isRow9Good() || isRow10Good())
{
Debug.Log("LOL");
}
}
The content of the functions is this:
Piece p1 = row1[0].ReturnPiece();
Piece p2 = row1[1].ReturnPiece();
Piece p3 = row1[2].ReturnPiece();
Piece p4 = row1[3].ReturnPiece();
if (p1.isTall && p2.isTall && p3.isTall && p4.isTall)
{
return true;
}
else if (p1.isRed && p2.isRed && p3.isRed && p4.isRed)
{
return true;
}
else if (p1.isHollow && p2.isHollow && p3.isHollow && p4.isHollow)
{
return true;
}
else if (p1.isCylinder && p2.isCylinder && p3.isCylinder && p4.isCylinder)
{
return true;
}
else
{
return false;
}
And the others are the same, just instead of row1[] it's row2[].
If the first function is true, the console logs the "LOL" message, but if the second or the third and so on are true, the value is not getting outputted. I tried changing the functions' places, every time it only cares if the first one is true, and the rest are ignored.
What would you say I am doing wrong? :D
else if (p1.isRed && p2.isRed && p3.isRed && p4.isRed)
{
return true;
}
else if (p1.isHollow && p2.isHollow && p3.isHollow && p4.isHollow)
{
return true;
}
else if (p1.isCylinder && p2.isCylinder && p3.isCylinder && p4.isCylinder)
{
return true;
}
if I'm understanding you correct if all four pieces in a row are red its not returning true. You need to double check if the 'isRed' is set properly. if p1.isRed and p2.isRed and p3.isRed and p4.isRed then it will return true no matter what. Also double check if you meant to put || instead of &&.

C# Character count condition

how can i put condition here. Like if i Inputted a 4 digit character, it'll put a Prefix which is "F-".
try
{
Service1 ws = new Service1();
if (e.KeyChar == (char)13 && button1.Enabled == true)
{
inputtxt = F.Text.ToString();
showpic(inputtxt);
if (ws.VerifyEID(inputtxt) == false)
{
MessageBox.Show("You have entered an incorrect Employee ID. Please try again!", "Attendance Monitoring System", MessageBoxButtons.OK, MessageBoxIcon.Warning);
F.Text = null;
}
else
{
panel1.Visible = false;
SqlToText(inputtxt);
ShowOffset(inputtxt);
if (BtnTimeIn.Visible == true)
{
BtnTimeIn.Focus();
}
else
{
BtnTimeOut.Focus();
}
}
}
Help me please, thankyou.
You can insert this in your code:
inputtxt = inputtxt.StartsWith("F-") ? inputtxt : "F-" + inputtxt;
But I would personally have that prefix on the textbox to make it clear for the users what to type in and have them type less characters.

C# or vba check box

I'm new here and I have a problem (I think the solution is simple, but I can't solve this problem alone). I have to throw a few checkbox on userform (that is simple) but when I write something like this:
if(checkBox1.Checked)
{
MessageBox.Show("ok1");
}
else if(checkBox1.Checked && checkBox2.Checked)
{
MessageBox.Show("ok2");
}
else
{
MessageBox.Show("co nie tak");
}
always get "ok1" MsgBox...
Any ideas what I'm doing wrong? Thanks for helping.
The if statement will always go into the first block that is true. So if checkbox1 is checked you will always get "ok1". You can never get into the second block ( "ok2" ) because if it is true, the first check would also be true.
I think you want to switch your checks:
if(checkBox1.Checked && checkBox2.Checked)
{
MessageBox.Show("ok2");
}
else if(checkBox1.Checked)
{
MessageBox.Show("ok1");
}
else
{
MessageBox.Show("co nie tak");
}
You may also be looking to build up your string by adding to it. The += means add to the end of the string.
My example code is just an example, since I don't really know what you are trying to do, but it might give you some ideas.
if (checkBox1.checked )
{
mic.HTMLBody = "1) Example1";
}
if ( checkBox2.checked )
{
mic.HTMLBody += "<br>"""2) Example2";
if ( ComboBox2.Text == "Pan" )
{
mic.HTMLBody += "<br>Pana";
}
}
from the code i see if checkbox1.checked is true then "ok1" should display and the second an third evaluations would never be evavluated. if checkbox1.checked is false then only the third option would be evaluated and the second option should never be evaluated at all. Should be more like:
if (checkBox1.Checked)
{
if (checkBox2.Checked)
{
MessageBox.Show("ok2");
}
else
{
MessageBox.Show("ok1");
}
}
else
{
MessageBox.Show("co nie tak");
}
As it is currently written, it is impossible for it to enter the else if, because whenever the else if condition is true, the if condition is also true.
It goes from up to down, the first that is true is entered and the rest are ignored.
Instead you should switch their place as follows:
if(checkBox1.Checked && checkBox2.Checked)
{
MessageBox.Show("ok2");
}
else if(checkBox1.Checked)
{
MessageBox.Show("ok1");
}
else
{
MessageBox.Show("co nie tak");
}
A little unclear what you really want shown, but if you want it to first show ok1 and then ok2 then you can do this:
if(checkBox1.Checked)
{
MessageBox.Show("ok1");
if(checkBox2.Checked) {
MessageBox.Show("ok2");
//MessageBox.Show("ok1 ok2"); //If you want to show them both at the same time
}
}
else
{
MessageBox.Show("co nie tak");
}
I tried this one on a Console and it might be the logic you need. The inline comments will give you a bit of insight of what is doing what:
check1 = true;
check2 = true;
if (check1)
{
if (check2)
{
// Prints if BOTH check1 and check2 are TRUE
Console.WriteLine("ok2");
}
else
{
// Prints if ONLY check1 is TRUE
Console.WriteLine("ok1");
}
}
else
{
// Prints if BOTH check1 and check2 are FALSE
Console.WriteLine("co nie tak");
}
bool Check = checkBox1.Checked;
bool Check2 = checkBox2.Checked;
if (Check == true && Check2 == true)
{ MessageBox.Show("ok 1 & 2"); }
if (Check == true)
{ MessageBox.Show("ok 1"); }
if (Check2 == true)
{ MessageBox.Show("ok 2 "); }
else
{ MessageBox.Show("Not Checked"); }

Unity C# coroutine not working

I am trying to make a Simon game. Obviously, when one color is displayed, it should wait a second or so. I created a coruotine for when the game is showing you what to do. Inside the coroutine, it is supposed to pause first, which when I run the game, it does. Then it goes through and chooses a color and stuff. Then it should loop back up(I made a loop) and pause again, and do everything again. The problem is, the pause only works the first time. Then it displays the other colors for like half a second and ends. I don't understand why once it loops it seems to do everything except for the pause. Here is my code:
void Update () {
if (show == true) {
StartCoroutine(Show());
}
}
IEnumerator Show() {
do {
yield return new WaitForSeconds(2f);
round ++;
if (round == 1) {
on = Random.Range(1,5);
}
if (round == 2) {
on = Random.Range(1,5);
}
if (round == 3) {
on = Random.Range(1,5);
}
if (round == 4) {
on = Random.Range(1,5);
}
// Turn on/off lights
if (on == 1) {
green.GetComponent<Renderer>().material = greenMat;
}
if (on != 1) {
green.GetComponent<Renderer>().material = greenOff;
}
if (on == 2) {
red.GetComponent<Renderer>().material = redMat;
}
if (on != 2) {
red.GetComponent<Renderer>().material = redOff;
}
if (on == 3) {
yellow.GetComponent<Renderer>().material = yellowMat;
}
if (on != 3) {
yellow.GetComponent<Renderer>().material = yellowOff;
}
if (on == 4) {
blue.GetComponent<Renderer>().material = blueMat;
}
if (on != 4) {
blue.GetComponent<Renderer>().material = blueOff;
}
}while(show == true);
}
I wrote a coroutine which may help you. Put it on start.
IEnumerator Show()
{
while (true) // or show
{
yield return new WaitForSeconds(2f);
round ++;
if (round >= 1 && round <= 4)
on = Random.Range(1,5);
green.GetComponent<Renderer>().material = on == 1 ? greenMat : greenOff;
//Same for the other...
}
}

Button not working on an != if statement

I'm trying to replicate the Mastermind game within c# and have hit a hurdle, so to speak. The problem I'm facing is at the stage where player 2 guesses which 3 checkboxes are correct from the 6 available. (8 rows for 8 attempts/lives at guessing). The code I have works when player 2 guesses the correct checkboxes, however when the incorrect checkboxes are selected and the "guess" button is clicked nothing happens. I have a second if statement to check this but obviously something must be wrong. The code for the button click event is:
private void Guess_button_Click(object sender, EventArgs e)
{
int boxesChecked = 0; // Default value
CheckBox[] checkBoxArray = new CheckBox[]
{ checkBox1, checkBox2, checkBox3, checkBox4, checkBox5, checkBox6 };
for (int i = 0; i < checkBoxArray.Length; i++)
{
if (checkBoxArray[i].Checked)
boxesChecked++;
}
if (boxesChecked > 3)
MessageBox.Show("You have checked " + boxesChecked.ToString() +
" checkboxes. Only 3 are allowed.");
else if (boxesChecked < 3)
MessageBox.Show("You have checked " + boxesChecked.ToString() +
" checkboxes. Please choose 3.");
if (checkBox1.Checked == cb1)
if (checkBox2.Checked == cb2)
if (checkBox3.Checked == cb3)
if (checkBox4.Checked == cb4)
if (checkBox5.Checked == cb5)
if (checkBox6.Checked == cb6)
{
MessageBox.Show("Congratulations, You Win!",
"Game Won");
if (MessageBox.Show("Would you like to play again?",
"Play Again?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
p1input restart = new p1input();
this.Close(); // Close current window
restart.Show(); // Open restart (instance of p1input)
}
else
{
Environment.Exit(0); // Terminate Application
}
if (checkBox1.Checked != cb1)
if (checkBox2.Checked != cb2)
if (checkBox3.Checked != cb3)
if (checkBox4.Checked != cb4)
if (checkBox5.Checked != cb5)
if (checkBox6.Checked != cb6)
{
MessageBox.Show("Unlucky, Guess Again!");
checkBox1.Visible = false;
checkBox2.Visible = false;
checkBox3.Visible = false;
checkBox4.Visible = false;
checkBox5.Visible = false;
checkBox6.Visible = false;
}
}
}
Ok, let's go. There a few things to review at your code:
1. How many checkbox are checked?
Let's use a little lamba to make that for a little bit prettier:
boxesChecked = checkBoxArray.Where<CheckBox>(x => x.Checked).Count();
2. If the user doesn't have checked 3 checkboxes, let's show the message and leave the method!
It's a little bit simplified too, you may wish to change it:
if (boxesChecked != 3)
{
MessageBox.Show(string.Format("You have checked {0} checkboxes. Please choose 3.", boxesChecked));
return;
}
3. Verify the result
Let's change those if a little bit. Notice the main else condition (player lost!):
if (checkBox1.Checked == cb1
&& checkBox2.Checked == cb2
&& checkBox3.Checked == cb3
&& checkBox4.Checked == cb4
&& checkBox5.Checked == cb5
&& checkBox6.Checked == cb6)
{
MessageBox.Show("Congratulations, You Win!", "Game Won"); // Display MessageBox
if (MessageBox.Show("Would you like to play again?", "Play Again?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
p1input restart = new p1input();
this.Close(); // Close current window
restart.Show(); // Open restart (instance of p1input)
}
else
{
Environment.Exit(0); // Terminate Application
}
}
else
{
MessageBox.Show("Unlucky, Guess Again!");
checkBox1.Visible = false;
checkBox2.Visible = false;
checkBox3.Visible = false;
checkBox4.Visible = false;
checkBox5.Visible = false;
checkBox6.Visible = false;
}
Please note that I'm not saying that this is the best design for a game, I'm just pointing out a few things to change on your code.
UPDATE
Based on spender's comment, let's review your method. Please, check it out:
private void Guess_button_Click(object sender, EventArgs e)
{
int boxesChecked = 0; // Default value
List<CheckBox> AllTheCheckBoxes = new List<CheckBox> { checkBox1, checkBox2, checkBox3, checkBox4, checkBox5, checkBox6 };
boxesChecked = AllTheCheckBoxes.Where<CheckBox>(x => x.Checked).Count();
if (boxesChecked != 3)
{
MessageBox.Show(string.Format("You have checked {0} checkboxes. Please choose 3.", boxesChecked));
return;
}
if (AllTheCheckBoxes.Any<CheckBox>(x => x.Checked != Convert.ToBoolean(x.Tag)))
{
MessageBox.Show("Unlucky, Guess Again!");
AllTheCheckBoxes.ForEach(x => x.Visible = false);
return;
}
MessageBox.Show("Congratulations, You Win!", "Game Won"); // Display MessageBox
if (MessageBox.Show("Would you like to play again?", "Play Again?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
p1input restart = new p1input();
this.Close(); // Close current window
restart.Show(); // Open restart (instance of p1input)
}
else
{
Environment.Exit(0); // Terminate Application
}
}
Notice that I'm using the Tag property. It's an arbitrary string, that developer may use for any purpose. Here I'm expecting that the correct value (true or false) is stored at this property.
UPDATE 2
Regarding OP comment about finding all the checkboxes (looks like its 48 total).
You can use the following statement (understand it and improve it to your needs).
List<CheckBox> AllTheCheckBoxes = this.Controls.AsQueryable().OfType<CheckBox>().Where(x => x.Tag != null).ToList();
Your check for an incorrect value appears to be inside the braces of the if statements for when the user guesses correctly.
In other words, it won't ever be hit. You need to break it out of the braces so it runs.
Like others said, all those nested ifs are going to hurt you in the end. Consider cleaning up that bit so you can understand what's happening better.

Categories