-2

I just started programming inside Unity, and I am trying to make a very basic countdown timer using a FOR loop. However, I don't undsertand why VS asks for a ; at the start of my loop

Here is the script :

public float startTime = 10;

void Start()
{
    
}

void Update()
{
    for (startTime = 10; startTime > 0) // Unity says there should be a ; here //
    {
        startTime -= Time.deltaTime;
        Debug.Log(startTime);
    }
        
}

Error CS1002 : ";" requested at line 15.

I've verified in the scripting refernce, and there is never any ";" when starting a loop. Is this linked to a syntax error earlier in the code?

Ruzihm
  • 19,749
  • 5
  • 36
  • 48
  • 2
    for...loops are composed by three parts. The initialization, the exit condition, the increment. Each part is separated by a semicolon. You are not required to give all three parts but the semicolon is still required – Steve May 06 '21 at 20:18
  • 1
    Which scripting reference? – General Grievance May 06 '21 at 20:19
  • Syntax errors aside, don't use a for loop in `Update` like this or it'll run all within the span of a single frame. You should consider using something like a coroutine instead. – Ruzihm May 06 '21 at 20:39
  • Does this answer your question? [How to make the script wait/sleep in a simple way in unity](https://stackoverflow.com/questions/30056471/how-to-make-the-script-wait-sleep-in-a-simple-way-in-unity) – Ruzihm May 06 '21 at 20:42
  • You shouldn’t use a for loop here, just subtract Time.deltaTime at the end of every update function. A for loop keeps going until it is complete. This would not make a timer, because it would be finished in one frame. – gbe May 06 '21 at 22:03

1 Answers1

0

Summarizing what Steve said in the comments, you're missing the last part of the loop definition.

The "startTime -= Time.deltaTime" should be after the stop condition. I suppose there's nothing stopping you from writing the last bit in the loop itself like you have it, but that's not really standard.

At the very least, you'll still need a semicolon after the stop condition, like Steve said.

It would look something like

for(startTime = 10; startTime > 0; startTime -= Time.deltaTime){ ... }
F0urL1ghts
  • 100
  • 7
  • That wouldn't be semantically the same as the OP's code (if they insert the missing semicolon). Their version would log `10-Time.delta` as the first value, whereas yours would log `10` – pinkfloydx33 May 06 '21 at 22:53
  • 1
    @pinkfloydx33 That's a very good point. I hadn't considered that. I suppose startTime could be initialized to 10 - Time.deltaTime to get the same behavior. – F0urL1ghts May 06 '21 at 22:55
  • I solved the problem with an if loop, but I'm keeping this thread preciously in case i need halp later for FOR loops. – BastosIsReal2401 May 07 '21 at 12:48