While Lua is really fast to execute in a bubble, it can quickly start to take its toll when it starts to reference stuff in the outside world. While the interpreter that we’re using drastically reduces the overhead of such references, there is still an overhead.
Anything in the API Reference should be used as lightly as possible.
Does it already exist?¶
The Unity Tools have a lot of built in native components that cover a lot of different things that you might want to do. Before you think about writing a script, check out the Track Components list under the Custom Tracks section and see if there is already something there.
While the sample scripts provided give you a lua implementation of some of these behaviours, these are only supposed to be examples of code to help get to grips with using Lua.
Get rid of functions you’re not using¶
If you’re not using a function that the template script contains, remove it. Every function gets called if it exists, which takes resources as the game has to subscribe the call event internally and then has to run the function every time the game triggers whatever it is the function is an extension of.
Put briefly, the dos and the donts¶
- Use Lua to create reactive behaviours. This is what Lua is best at and you actually have a lot of headroom to work with when it comes to one off events
- Use Update methods sparingly and use the appropriate tick rate.
- Use Fixed Update for very basic tasks (in most cases you shouldn’t even need it)
- Have tons of API references in an Update function
- Perform huge amounts of complicate math in an Update function
- Use FixedUpdate for animations. FixedUpdate is for physics and is called 200 times a second
Tick rates and you¶
You can set the rate at which a lua scripts Update method is ticked at using the Update Tick Rate option in the Lua Runner component.
By default this is set to 60, which is more then enough. You can go higher or lower but it’s not reccomended that you do go higher.
- 15 ticks is good for long term state checks, like checking per tick if a ship is still performing a perfect lap and doing something with that information.
- 30 ticks is good for more general behaviours, such as altering ship data like its health.
- 60 ticks is good for animations
- 90 and 120 ticks are not really needed, you could make smoother looking animations for higher refresh rate displays with these but this is still not reccomended.
- Unlocked will call the update for every rendered frame. Do not use this unless you need to access very time sensitive information
Tick rates are not 100% accurate since they’re calculated per frame and not on a separate timer. Make sure you’re multplying values by unscaledDeltaTime or deltaTime for correctly timing everything regardless of the framerate.
It’s not possible for higher ticks to run at the intended tick rate on lower framerates. They will be capped to the framerate itself, again making the deltaTime values very important.