https://github.com/codartesien/godot-source-generators-csharp
A collection of source generators for Godot 4+ C# projects.
https://github.com/codartesien/godot-source-generators-csharp
csharp godot source-generator
Last synced: 3 months ago
JSON representation
A collection of source generators for Godot 4+ C# projects.
- Host: GitHub
- URL: https://github.com/codartesien/godot-source-generators-csharp
- Owner: codartesien
- Created: 2025-02-05T15:22:11.000Z (over 1 year ago)
- Default Branch: master
- Last Pushed: 2025-02-05T23:11:29.000Z (over 1 year ago)
- Last Synced: 2025-02-16T07:18:01.976Z (over 1 year ago)
- Topics: csharp, godot, source-generator
- Language: C#
- Homepage:
- Size: 11.7 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Godot C# Source Generators
A collection of source generators for Godot 4+ C# projects.
## Installation
Git clone this repository and build the project using `dotnet build`.
Then reference the generated assembly in your main project:
```xml
```
If you need to debug the source generators, you can add the following to your main project file:
```xml
true
$(BaseIntermediateOutputPath)Generated
```
## Source Generators
### SceneNodeResolver
This source generator generates code to automatically resolve scene nodes in your scripts.
Your scene nodes must have a `SceneNode` attribute with the path to the node in the scene.
It generates a partial class with a public `ResolveNodes()` method that you can call in your `_Ready()` method.
```csharp
using Godot;
using Codartesien.SourceGenerators;
public partial class MyNode : Node
{
[SceneNode("Sprite")]
private Sprite _sprite;
[SceneNode("%MyLabel")]
private Label _label;
public override void _Ready()
{
base._Ready();
ResolveNodes();
}
}
```
### DependencyResolver
This source generator generates code to automatically resolve dependencies targeting Godot globals (aka autoload or singletons) in your `Node` scripts.
Think of this as a simple dependency injection system for your Godot project.
> [!NOTE]
> As this generator relies on the `GetTree()` method, `[InjectDependency]` attribute can only be used in scripts that inherit from `Node` (so not in raw C# classes).
For example, if you add the `HappinessManager` class as a global node in your project, you'll be able to inject it in your scripts using the `[InjectDependency]` attribute.
```csharp
using Godot;
using Codartesien.SourceGenerators;
public partial class MyNode : Node
{
[InjectDependency]
private HappinessManager _happinessManager;
public override void _Ready()
{
base._Ready();
ResolveDependencies();
_happinessManager.DoSomething();
}
}
```
You can use the `[InjectDependency]` attribute on any property which related to a global node in your project.
Under the hood, the source generator creates a dictionary of all children of the `root` node and inject them in the fields marked with the `[InjectDependency]` attribute.