- Home /
on / off if statement C#
Hi again,
Oh my gosh I'm learning so much! Thank you all for helping :)
I'm having difficulty working out how to do the following in C#:
Ive got this script running once per second via a yield. Being that there is the potential for it to run hundreds of times, how can i check if it's been run once so that it doesn't keep repeating? I don't want to stop the yield as such but only 'shut off' an if statement and i want to add more if statements so I'm guessing i need some sort of variable thats local to the if statement somehow?
I tried using a bool but obviously it just keeps changing the variable back to false and continues to run.
bool togglething = false;
if(convertToSeconds <= 20788 && convertToSeconds >= 18788 && togglething ==false){
togglething = true;
print("I'm in");
}
Thanks you awesome dudes! I will have your babies if you can work this out :P
Answer by Kiwasi · Nov 30, 2014 at 07:57 AM
Declare the bool at the class scope
bool togglething = false;
void MyMethod(){
if(convertToSeconds <= 20788 && convertToSeconds >= 18788 && togglething ==false){
togglething = true;
print("I'm in");
}
}
Note that I already have enough babies, but I do appreciate the offer.
Thanks Bored$$anonymous$$ormon,
Ok so maybe babies are off the cards but i can roll with that :P
I'm thinking declaring it at a class level has the yield not recognising the change? I'm not sure, what do you think?...
private bool togglething = false;
IEnumerator $$anonymous$$y$$anonymous$$ethod() {
while(true){
yield return new WaitForSeconds(1f);
int convertToSeconds = 18811;
if(convertToSeconds <= 20788 && convertToSeconds >= 18788 && togglething ==false){
print("I'm in");
togglething = true;
}
}
}
It kinda gets stuck on false therefore printing "I'm in" several hundred times :/
Any ideas?
Thanks again :)
Oh wait! That above code does work, I'm not sure what i did for it not to work in the first place.
Thank you so much Bored$$anonymous$$ormon!!! Appreciate you wisdom! Xoxo :P
Occasionally Unity does not import code the instant you save it. Or you forget to save your changes. Glad it works. Be sure to click the accept button.
Also converted your answer to a comment.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
OnTriggerEnter2D with multiple objects 0 Answers
OnTriggerEnter function in c# 0 Answers
What's wrong with my code? C# 1 Answer