SmartlyDressedGames / Unturned-3.x-Community

Community portion of the Unturned-3.x repo. If you have access to the source code you can find it here:
https://github.com/SmartlyDressedGames/Unturned-3.x/
88 stars 18 forks source link

Speed up InteractableFarm.Update() to improve FPS #4718

Closed asineth0 closed 1 month ago

asineth0 commented 1 month ago

I see in InteractableFarm.Update() it seems to check whether the plant is grown and swap out the game objects.

// Token: 0x0600216F RID: 8559 RVA: 0x00086038 File Offset: 0x00084238
private void Update()
{
    if (!Dedicator.IsDedicatedServer && !this.isGrown && this.checkFarm())
    {
        this.isGrown = true;
        Transform transform = base.transform.Find("Foliage_0");
        if (transform != null)
        {
            transform.gameObject.SetActive(false);
        }
        Transform transform2 = base.transform.Find("Foliage_1");
        if (transform2 != null)
        {
            transform2.gameObject.SetActive(true);
        }
    }
}

The unfortunate problem with this is that it requires calling Update() very often and while this function is empty on the server, it still wastes a lot of CPU. For example, with 8000 crops, disabling the InteractableFarm component on the server can cut the CPU usage nearly in half.

Moving all of this into something like InteractableManager would be a relatively simple fix for this and would improve performance on servers with lots of plants in-game (eg. RP servers for example). Or alternatively, just making sure the Update() function doesn't exist on the server so Unity doesn't waste CPU calling it.

SDGNelson commented 1 month ago

It's a fair point that this is poorly implemented. For the next update I'll remove it from the dedicated server build as you suggested. Ideally, I'd like to implement some sort of timer queue in the future for things like plants finishing growing, resetting objects, respawning, etc.

Jdance-Media commented 1 month ago

If I'm not mistaken, Transform.Find ought to be somewhat slow. Might be worth keeping the foliage transforms as nullable fields.

SDGNelson commented 1 month ago

Thanks Jdance, you're right that Transform.Find can be slow - in fact there was an issue relatively recently with a plugin UI that had thousands of children - but in this case it's only finding those two direct children on the frame the plant state changes so it shouldn't have a particularly noticeable impact. If it were using Find every frame or there were more to search through (deep hierarchy) then it would almost certainly make sense to save a reference to them.

Jdance-Media commented 1 month ago

Ah I see. Makes sense. 👍