Say I have a method which contains int variable that is displayed to user on screen and it needs to be always updated (the number keep changing realtime).
However I cannot use the Update() method since the said method is called from another method.
Now is it still possible to produce the text that updates in realtime without being placed inside Update()?
You still can use Update, but in this case you should introduce a flag (a boolean variable). You will be able to control this variable from another method. If the variable is true, then change text, if it is false dont do that.
private bool flag;
void Update()
{
if(flag)
{
// Do stuff you want
}
}
void AnotherMethod()
{
// Do some stuff
flag = true; // I want the text to change
}
If you still dont want to use Update, then coroutines are great as well. More about them you can find in google.
Skip Update() and coroutines. Use events. Any time you find yourself continuously polling a variable for changes, you will almost certainly be better served by events.
Because coroutines and update are examples of constantly polling for changes in data. You’re running code that checks whether data has changed, and that code takes CPU cycles. Events, on the other hand, ONLY run if there’s been a change, meaning that CPU cycles aren’t being wasted constantly checking to see if something’s changed when nothing has changed.
If you want to get ahold of a friend, but they’re not answering their phone, it makes a lot more sense to just leave a message and have them call you back than to keep calling every second until their availability changes.
I see. For your example that is true. Events should be used. But the question of this topic is not the same. Author doesnt want to check if something has changed. He actually changes it continuously, doesnt he? Or I just misunderstood the task?
As I understood, text will be changed every frame.
If the frequency of the change is higher than the frequency Update is called, it isn’t any better to use an event. Otherwise, it’s better, both efficiency-wise and from a structural point of view. I had forgotten that he changes the value continuously, but he probably does so from another Update(), and a MonoBehaviour running an Update loop to continuously poll an external object is going to carry significantly more overhead than an event triggered from the external object.