how do I create a static c# class without inherenting from Node?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Wender Alves Libório
:warning: Old Version Published before Godot 3 was released.

I want to create a Utils with consts and static functions, how do I create a file so godot load this file containing only this static class, I tested a workaround with creating this class in the same file where Node is inherented from. I am using 3.0 beta1.

:bust_in_silhouette: Reply From: Zylann

Go to script editor, File → new.
You should be able to create a new C# script, choose a path and save.
Modify the example code with what you want.
That should allow you to create any script, even if it’s not inheriting anything special from Godot.
You can also create the script from the shortcut “add script to node”, and then remove the script from the node.

Note: this approach also works for GDScript for creating utility functions.

Note 2: if you are using beta 1, it’s possible that Godot won’t update the .csproj, which leads the file to not be recognized when compiling. This has been reported on Github and will get fixed later. But you can still workaround this by using an IDE like Xamarin MonoDevelop or Visual Studio, which can update the .csproj with new C# files created arbitrarily.

I got the script working, but for those seeking to no inherent from Node, you can inherent from Reference and Object which dont use garbage_collector!

Wender Alves Libório | 2017-12-17 13:56

You can also inherit nothing. If your class only contains static helper functions, you can even declare your class static:

static class Helpers // also static classes don't allocate memory, so no GC
{
    public static int Sum(int a, int b)
    {
        return a + b;
    }
}

// Usage:
Helpers.Sum(42, 43);

If you don’t have a static class and if you use new on it, inheriting Reference or not will not prevent C# garbage collection to happen anyways. Not sure what you meant here?

Zylann | 2017-12-17 15:32