Every second function

Hi. Unity 5 made allot of improvements, but there is 1 function i would like to see in the future to speed
up the development process and performance.

Today we have this frame realtime functions:

void Update () // every frame
void LateUpdate() // Every frame after Update frames

Now allot of times i do construct my own logic to have every second events (with Deltatime), because many things does not have to be every frame. It works and thats fine.

But It would speed up the development practice if we had a example void DeltaEvent() function that happen based on time and not frame. This is useful for logic implementation, example distance check, UI event etc.

Discuss?

Invoke, InvokeRepeating, Coroutines, your own threading solution. Unity has many ways to do what you want.

1 Like

Yes there are ways to use it like that, but i dont think you get what i am talking about. I am talking about Mono function, not IEnumerator or Deltatime relevance, i already stated that solution. IEnumerators needs to be started from another function.Also when you Invoke.

Let me clarify

void Update()
{
  // Every thing you put here will be handled every frame
}

void SomeNewUnity5FunctionTimeBased()
{
  // Every thing you put here will be handled every second
}

Everyone understands what you’re saying, there’s simply no reason to do it. A coroutine can do exactly what you want far more flexibly than a “built-in” function like that. It saves absolutely nothing in development time, it would be slower than coroutines because it’s found and stored using reflection, and you wouldn’t be able to control the intervals or logic the way that you can with a coroutine either.

And a coroutine is just one of many alternatives, all of them better.

2 Likes

Coroutine are not the solution nor the best practice for what i am talking about. The best solution at this point of time, is to use Time relevance intervals (since this what you want to achieve) Corotines are not ment for this task, even you can delay by time.

The solution (this is taken from Unity advice, so trolling is kinda pointless here)

Performance friendly code:

float TimeInterval ;

    void LateUpdate()
    {
        // ones per in seconds
        TimeInterval += Time.deltaTime;
        if (TimeInterval >= 1)
        {
                      TimeInterval = 0;
                       // Performance friendly code here
         }
    }
2 Likes

I also agree that unity should NOT have built - in functions that fire at specific time intervals.

As you’ve proven, you could easily replicate the behaviour yourself.

In your example, you’ve written something that fires every second. Good. Great!

Are you suggesting that unity should have an OnEverySecond() function?

What if i wanted to fire something every two seconds? Or every five?

You can see that if unity were to add functions for every possible time interval, the api would fill up with quite quickly and it would not make a lot of sense.

You could write your own timer class:

public class Timer {

     float seconds;
     float timeStamp;

     public Timer(float seconds)
     {
          Set(seconds);
     }

     public void Set(float seconds)
     {
           this.seconds = seconds;
           this.timeStamp = Time.time;
      }

     public bool ExpireReset() {
          if (Time.time >= timeStamp + seconds) {
                Set(seconds);
                return true;
          }
          return false;
     }
}

Which on its own would be fine, but you could also extend MonoBehaviour so that it fires events at intervals you choose:

public class IntervalBehaviour : MonoBehaviour {
    Timer secondTimer;

    void Awake()
    {
          secondTimer = new Timer(1f);
    }

    void Update() {
          if (secondTimer.ExpireReset())
                  EverySecond();
    }

    public virtual void EverySecond() {}
}

You could extend your behaviours from this and have a EverySecond function on each of them, that way. OR, for double extra try-hard mode, you could do this:

public class IntervalMessages : IntervalBehaviour {

         public override EverySecond() {
                gameObject.SendMessage("OnEverySecond", null, SendMessageOptions.DoNotRequireReceiver);
         }
        
}

And voila. We’ve now implemented what you wanted in the first place. Place this last component on any gameObject, and any behaviour it contains with a “void OnEverySecond();” will fire every second.

Sometimes, you’ve got to do the work youself. Unity can’t do EVERYTHING for you.

3 Likes

This is why we have a discuss right? :slight_smile: its great to hear peoples input on this subject, there are solutions (yours good example also) so this is not a issue discussion really. Its just that it would be nice to have some function that works better with time, rather than frame. (Of course we can implement this our self, its just that time is a big factor in any games, why hack basic needs?

Frames and Time are pretty far apart, even they are related.

Lets say Unity made a function that worked kinda similar to IEnumerator Coroutine, just without the start and stop and 100% independed, you can control time just fine with the Coroutine function, wouldn’t be a big problem to implent something similar. Would give more control and overview of time relevance. I am not sure if Coroutine are based on COM interoperability, any one?

How can you fill up the API ? Didn’t know such a limitation did exist :stuck_out_tongue:

Aaaaaaaaaand… you have the expertise to determine this why?

Coroutines accomplish this perfectly.

You do know that the automatic code actually has another function that calls things like Update and LateUpdate for you. You’re just complaining that YOU have to write the code to start the coroutine.

How about you write a class that scans via reflection your components for methods with a name that matches the signature you want, generates the delegate, and calls it on the interval as defined in its name.

Invoke and InvokeRepeating deal with time.

WaitForSeconds deals with time.

A LOT of functions deal with time.

If you’re upset that the functions don’t actually wait that exact number of seconds, and instead are the frame nearest that duration of time. Well that’s not going to change. Unity only lets you update between frame rendering (on Update). With good reason, if you altered the state of the game during frame rendering, it could effect the look of the scene mid draw. You could end up with the top portion looking one way, and the bottom another.

This is the same reason you can’t update unity objects from another thread.

2 Likes

You clearly dont get it :slight_smile: I can see that a allot of people lack the knowledge around Coroutines, i am not going to elaborate on that. Better to go read Unity - Manual: Coroutines

Coroutine already has that, its just that Coroutines has some clear limitations(hence my thread on this). I hope your not against Coroutines. They are pretty good for there uses. But not for what i am talking about in all situations.

Yeah… I don’t get it.

I honestly don’t get what YOU’RE on about.

I do understand coroutines just fine. You linking to the documentation that shows examples about how to write a coroutine does not prove that they “are not the solution nor the best practice” for operating code on some interval of time.

3 Likes

Name them. Name what limitations they have that your solution remedies.

I’m not going to understand what you’re remedying if you don’t tell us what you’re remedying. Because they aren’t that “clear” to me.

2 Likes

Its good that you realized that, its a good start :slight_smile: Yield and take a chill pill lordofduct, read the link i gave you (read all of it), and the sense will come to you, no need for me to copy/past basic Unity documentations. Enumerator has limitations in Unity… Have a good evening.

Sure, you have a good evening as well.

I have to go read basic documentation on coroutines, because clearly I don’t know how they work.

I’ll just leave this right here.

2 Likes

I think @lordofduct is frustrated because you are trying to hold an instructional, knowledgable demeanor when it’s very obvious that you have no idea what you’re talking about.

I’d prefer if we could keep nonsense like this out of the unity forums, so lets just call this thread closed.

5 Likes

Did you really post that code if your own post had no meaning? You clearly understood where i was going with this.

I’m with @Ironmax on this one.

I also think Unity needs to integrate a “Make MMO” button, since that would save a lot of people so much time in making their games.

And would it kill them to have a couple gun models included and some pre-made levels so I can get my FPS off the ground sooner?!

6 Likes

To be fair, this code has some potential pitfalls. If you are quibbling about the few bytes of garbage created by coroutines, it’s worth looking closely at this too.

It will suffer from accumulating floating point errors each frame. This is typically not a huge deal, but the accuracy will effect some games. Coroutines and invoke do not suffer from this problem.

A bigger accuracy issue is abandoning the partial deltaTimes where the second mark is crossed mid frame. Coroutines will face this problem, I don’t believe invoke will (but it’s worth checking).

If you want performant code, but are not overly concerned about accuracy, use a coroutine. If you need more precise time, and performance is not an issue, you are better checking against Time.time instead of using Time.deltaTime.

Either way if you really need this functionality, it’s trivial to build into your own functionality.

5 Likes

Good luck using Coroutines IEnumerator interface for every situation in your project. Your going to have some problem if you want to return data. Your just looping through generic collection, and there is no way you can check how many and what is running. Floating point errors with the code i posted have no place in reality. The code is taken from Unity expert advice http://docs.unity3d.com/Manual/MobileOptimizationPracticalScriptingOptimizations.html

Also Coroutines does work in relevance to frames, since Yield will wait for next frame
based on your time.

You can of course make allot of messy code and call it your own solution. You don’t have to comprehend the meaning of this thread.

Return data to what? A custom timer in Update doesn’t return data either. In both cases you are limited to manipulating state, rather then returning values. You can do this equally well through any of the methods described. Coroutines actually have the advantage of being able to declare local state that can persist between frames.

There are advantages and disadvantages to every method mentioned in this thread. Insisting one method is superior or inferior is silly. Use the method that best suits your project needs and be done with it.

3 Likes