How do i make a loop?

I know that in python to make a loop you need to do:
while True:
*text

but i know that in C# for unity uses things like:
Time.DeltaTime * 10 ect.

could i have help im making a loop by using this method??

thank you!

while(true)
{
   //Do something
}

Honestly though, you didn’t give much info. And you could just google search c# loops to learn more about them. But if you are looking for a more precise answer, you’ll need to describe what you are trying to do. Time.DeltaTime is used because of certain reasons, but it may or may not be what you need. It’s not needed to create a loop, so unless we have more info, we can’t say if you actually need it.

2 Likes

All that time.deltatime stuff you’re seeing will be part of what the loop is doing, it has nothing to do with the requirements of making loops themselves.
All you need is a condition to set whether the loop continues. This one will continue until hell freezes over.

while (MyWife.IsHappyWith(Me) == false)
{
    Me.TryToMakeHappy(MyWife);
}
3 Likes

Actually it will throw a compile time error. Double equals. :stuck_out_tongue:

Everyone has covered the mechanics of a loop well. But I feel this might not be exactly what you are asking for.

Check out Update. It’s a natural loop that executes once per frame.

Also check out coroutines. These are essential to make loops extend over multiple frames.

Isn’t for(int x = 0; x > 5; x++) a type of loop too? Or am I wrong on that one? Just out of personal curiosity.

Yes. C# supports for, foreach, while and do-while loops.

https://msdn.microsoft.com/en-us/library/f0e10e56(v=vs.90).aspx

1 Like

That it will ;), my bad

ok so how would i do something like this?:
while(true){
health - 1 // using time.deltatime
}

That’s not something you do in a loop. A loop will execute entirely, all of its cycles, in 1 frame. If you want to take health off over time then you need to do it in something that occurs over multiple frames.

Your options are either the update function (executes once per frame) or a coroutine (put simply it’s a function that can be split over multiple frames).

private void Update()
    {
        Health -= Time.deltaTime;
    }

will take off one health per second. You would multiply time.deltatime by something to change the rate of health loss.

1 Like

ive got new code but can you help me with this?
https://forum.unity3d.com/threads/i-have-an-error-plz-help.457477/

Also a coroutine would work for that.

1 Like