Page 1 of 1

How can I optimize Lua.IsTrue() on Update()?

Posted: Thu Jul 22, 2021 8:47 am
by vcesauron
Disclaimer: I am still a beginner at profiling code, so pardon me if I say anything stupid xD

Our game is suffering from intermittent freezes every other couple of seconds. After taking a look at the CPU Profiler and the Call Stack, blocks of GC.Alloc() and GC.Collect() caused by Lua.IsTrue(string) seem like the "culprit".
Screenshots
gc1.png
gc1.png (114.55 KiB) Viewed 379 times
gc2.png
gc2.png (194.01 KiB) Viewed 379 times
gc3.png
gc3.png (278.19 KiB) Viewed 379 times
The game relies on checking for many Lua conditions several times per frame, and the way I do it currently is calling Lua.IsTrue(condition) every time I need to check the value of condition.

I created some sort of manager to limit the number of calls to this function per frame since many of those aren't frame-critic, and I did reduce the number of calls per frame from +20 to 5 (a value chosen by me), but it still keeps causing freezes.

How can I keep checking for Lua conditions while avoiding the freezes?

Re: How can I optimize Lua.IsTrue() on Update()?

Posted: Thu Jul 22, 2021 9:05 am
by Tony Li
Hi,

Avoid checking Lua.IsTrue() continually on Update().

If you're checking Lua.IsTrue() on Update(), you're using polling. It's much more efficient to make your code event-driven.

For example, if you want to know when a variable "X" exceeds 10, write a C# method IncrementX(), like:

Code: Select all

public void IncrementX()
{
    int x = DialogueLua.GetVariable("X").asInt;
    x++;
    DialogueLua.SetVariable("X", x);
    if (x >= 10)
    {
        // Invoke some event here
    }
}
You can call that method in a C# script or in Lua (e.g., in a conversation node's Script field) by registering it with Lua.

For another example of event-driven checking, examine the "Shoot 5 Enemies" quest in DemoScene2. The Enemies' IncrementOnDestroy components increment a variable and then invoke an OnIncrement() UnityEvent. The scene only checks if the variable is >= 5 in this OnIncrement() event. It doesn't check every frame.

If that's not possible, switch the Dialogue System to use NLua.

Re: How can I optimize Lua.IsTrue() on Update()?

Posted: Thu Jul 22, 2021 9:22 am
by vcesauron
I'm gonna try the event-driven approach first.
Because I'm using booleans, most of the checks are Variable["X"] == true, but I'll try to apply the same logic.

If it doesn't work, I'll try NLua.

Thanks for the quick response!

Re: How can I optimize Lua.IsTrue() on Update()?

Posted: Thu Jul 22, 2021 9:26 am
by Tony Li
Glad to help!