- Home /
x=x Assignment made to same variable
I have this weird problem where I have a for inside of a coroutine, and I want to set the classic "int i=0" to be a variable that's passed to the coroutine, called "time", but the syntax is wrong so I have to say "time=time", it works but it says "hey dummy you are saying time is equal time".
IEnumerator RunTimer(GameObject obj, float time)
{
obj.GetComponent<Timer>().TimerStart.Invoke();
Debug.Log(obj.name);
for (time = time; time > 0; time -= Time.deltaTime)
{
currentTime = time;
yield return null;
}
TimerEnded();
}
I can fix it by making a new "float timer" and change it to "time = timer", which basically also does nothing.
So is this just a dumb unity alert or is there a correct way of doing this?
Answer by StevenUnu · Sep 16, 2018 at 03:22 PM
There is another easier way than transforming the for loop into a while loop. You see, you can omit the initializing in the for syntax. C# won't complain.
for(; time > 0; time -= Time.deltaTime)
This isn't really new^^. It always has been like that. Only the condition ( middle part ) is required. The first and third part is optional.
omg, I wrote new? I meant "another" ins$$anonymous$$d of "a new". $$anonymous$$y $$anonymous$$d plays tricks on me
Answer by SkaredCreations · Sep 16, 2018 at 09:29 AM
It's just a warning that you're writing a "strange" assignment because assigning itself to a variable does not make sense as it means nothing essentially, so the compiler is wondering if you meant something else. You can ignore this warning or just use a new variable in the "for" statements.
Or also convert the "for" loop into a "while" logic (best choice imo), for example:
while (time > 0f)
{
currentTime = time;
yield return null;
time -= Time.deltaTime;
}
Answer by Torqus · Sep 17, 2018 at 03:36 AM
Both answers work well, thanks. I actually ended "using" my problem because it helps me get the current time for other objects that need it.
for (currentTime = time; time > 0; time -= Time.deltaTime)
{
currentTime = time;
yield return null;
}
So the While example could have been useful too.
Your answer
Follow this Question
Related Questions
How to have a (wait) yield on a for loop? 0 Answers
How do I reset a for loop variable??? 3 Answers
Help With "For Loop" Not Working? 2 Answers
Using for ... var ... in loop to access variable. 1 Answer
Having Trouble with this For Loop 1 Answer