The question is answered, right answer was accepted
Optimization: how to do a checking less often than within an Update
Right now, this is my code (it is working):
void Update() {
if (Cardboard.SDK.Triggered) {
Application.LoadLevel(Application.loadedLevelName);
}
}
However, it is not needed to perform that check every frame. I'm trying to use the Update function as less as possible. It would be OK to perform that check every 0.5 seconds for instance. I have found the following possibilities:
InvokeRepeating(): I wonder if it would increase the performance somehow, or it uses Update internally.
FixedUpdate() after configuring Edit -> Project Settings -> Time -> Fixed Timestep: it would change the fixed timestep for the whole game, so I think it would not be a good idea.
Answer by hexagonius · Oct 19, 2015 at 10:53 AM
Use either invoke repeating, or your own Coroutine with a while true and WaitForSeconds in it. In your case performance won't be an issue at all though. Rule of thumb, develop first, find bottlenecks last.
Answer by Michael_Berna · Sep 26, 2019 at 09:18 PM
In case anyone else finds this old thread, here's a great method that helped me. Directly from Unity documentation:
Run code every [x] frames
If code needs to run frequently and cannot be triggered by an event, that doesn't mean it needs to run every frame. In these cases, we can choose to run code every [x] frames. it would be sufficient for our needs to run this code once every 3 frames. In the following code, we use the modulus operator to ensure that the expensive function runs only on every third frame.
private int interval = 3;
void Update()
{
if (Time.frameCount % interval == 0)
{
ExampleExpensiveFunction();
}
}
An additional benefit of this technique is that it's very easy to spread costly code out across separate frames, avoiding spikes. In the following example, each of the functions is called once every 3 frames and never on the same frame.
private int interval = 3;
void Update()
{
if (Time.frameCount % interval == 0)
{
ExampleExpensiveFunction();
}
else if (Time.frameCount % interval == 1)
{
AnotherExampleExpensiveFunction();
}
}
Original document: https://unity3d.com/es/learn/tutorials/topics/performance-optimization/optimizing-scripts-unity-games
To be even more performant, you could use "FixedUpdate" instead of "Update", if possible.
Follow this Question
Related Questions
Problem with Jump script 1 Answer
Further understanding Updated() vs FixedUpdate() 0 Answers
FixedUpdate() or Update() for setting velocities 0 Answers