- Home /
What is wrong with my c# switch statement?
Hello,
I made a switch statement to control the up and down movement for a pin. The script is attached to a simple cube and everything works fine because he prints everything in the log. What I want to do is: Click the cube once and the pin starts moving, click the cube again and it stops moving.
I think I am pretty close because I can either start it or stop it depending on what I change the ' state' value to. When I keep it on 1 it starts moving onclick but doesn't stop and vice versa.
Here is my code:
void Update ()
{
if (Input.GetMouseButtonDown (0)) {
pinToggle ();
}
}
void pinToggle ()
{
int state = 1;
switch (state) {
case 1:
pinmovement.pinStart = true;
Debug.Log ("PinStart state: " + pinmovement.pinStart);
break;
case 2:
pinmovement.pinStart = false;
Debug.Log ("PinStart2 state: " + pinmovement.pinStart);
break;
}
}
The pinmovement is another script that containts the pin code and pinStart is a boolean to control wether it has to move or not.
Thank you so much, it solved my problem! I probably would never have thought of that.
Answer by gjf · Nov 26, 2014 at 12:51 PM
line 10 is most of your problem - if you're only ever setting it to 1, you'll only ever be setting your variable to true
!
your pinToggle()
method could just do this:
void pinToggle()
{
if (pinmovement != null)
{
pinmovement.pinStart = !pinmovement.pinStart;
}
}
Your answer
Follow this Question
Related Questions
Why would my switch's case be correct but the output is not? 2 Answers
Adjusting location on save to avoid infinite loop. 1 Answer
want to convert too many if statements into 1 switch case statement. error help. 2 Answers
Why does only one object respond, while more objects have exact same script? 0 Answers