Freeze when using C# dynamic type

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Onizudo

My code for adding items to the inventory returns a simple response, a boolean ‘succeeded’ and an int ‘overflow’ if there were any units not added. I am using a simple class containing those fields and it works fine, but i saw that i could do it in a simpler way using anonymous objects and the dynamic type.
The issue i’m having is, the first time the code returns the dynamic variable, it freezes for 300ms. After that its completly fine, but the first time it happens, and i have pinpointed it to the fact i’m using dynamic, since when i revert the code to the class, the freeze disappears.

:bust_in_silhouette: Reply From: MisterAcoustic

Hello - I don’t have specific knowledge relating to how godot interacts with C#, but I do have a possible explanation.

You say it’s the first time you attempt to use dynamic. It sounds to me like you’re triggering the load of a library when you hit that code for the first time.

I would suggest moving your first use of dynamic somewhere that is more convenient to have the delay, perhaps at startup or during a scene transition. You can just make a trivial use of the type in order to trigger the load when you want.

Once the load is complete, things should stay loaded, and on your second use of dynamic, it should work smoothly.

I hope :).

Good luck.

I did a few more tests, using the profiler aswell for some insight. I tried moving the dynamic usage to another place and check the effects. The 300ms delay happens on the next physics interaction. For exemple, i used the dynamic on a new basic script, just setting it on _Ready() and attaching it to the player, so it happens when the player is loaded. The freeze only happens after some type of collision or change in collision like when i jump, its really wierd that a variable creation would cause a physics2d delay

Onizudo | 2020-05-19 00:41

Sorry my suggestion didn’t work out. At least you seem to have the tools to eventually work out what is happening.

MisterAcoustic | 2020-05-19 03:39

:bust_in_silhouette: Reply From: Onizudo

I found a bit of a work around since i still cannot find the cause and consequently fix the issue. What i did is i made a script that i attached to the map (it could be anything really, just make sure its the first thing the game loads) and inside it i defined a simple anonymous variable and accessed it. Like this:

public override _Ready()
    dynamic firstUse = new { dynamicTypeUsed = true };
    GD.Print("Dynamic type used: " + firstUse.dynamicTypeUsed.ToString());

What it does is forces the freeze to the startup os the map/game, making gameplay smooth. As i said, it doesn’t fix the issue, but its a simple way to work around it.