31 / GodotOnReady

A C# Source Generator that adds convenient onready-like features to your C# scripts in Godot Mono (3.x) without any reflection.
https://www.nuget.org/packages/GodotOnReady
MIT License
123 stars 13 forks source link

C# 8 Non-nullable property warning #35

Closed Bear-03 closed 2 years ago

Bear-03 commented 2 years ago

When using C# 8 Non-nullable types with GodotOnReady, Godot shows warnings similar to

<project folder>\GodotOnReady.Generator\GodotOnReady.Generator.GodotOnReadySourceGenerator\Partial__IdleState.cs(7,27): warning CS8618: Non-nullable property 'PlayerDetectionAreaPath' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. [<project folder>\ActionRPG.csproj]

This is a warning, so it doesn't beak any code, although it is still somewhat off-putting, specially as the script count increases.

Normally, one would write null! in the property declaration to give it a null value until _Ready() is called.

[OnReadyGet] private DetectionArea playerDetectionArea = null!;

This way, declaring the property as nullable is not necessary, and as that's the only time it will be null, it is perfectly safe.

A solution could be adding that to the PlayerDetectionAreaPath property if C# 8 is being used and non-nullable types are enabled. Making the property nullable would also work; as that property is only intented to be used by the generated source code (afaik), it wouldn't result in developers having to write pointless null checks.

31 commented 2 years ago

Making the property nullable would also work; as that property is only intented to be used by the generated source code (afaik), it wouldn't result in developers having to write pointless null checks.

I much prefer this, I don't want to inject hidden nulls into people's scripts by default. 😄

I haven't looked into yet how to detect nullable project context in a source generator. (I don't think I can just slap in some #nullable directives, because I want to preserve compatibility with at least the default C# version Godot 3.x ends up with.)

31 commented 2 years ago

I pushed 1.1.6 with a fix, should be available shortly to try out.