I mean, e.g. GetComponent() should return not just T, but T?, and other similar things.
Is there even a plan to do that in the future?
There is no difference when compared to the current API. All reference types have the possibility to be null by default, it would only make for things like TryGetComponent where if true it could have a hint for the IDE that output will not be null.
The point is that, there will be no warning for the example below, but it should be if nullables is enabled
public class Card : MonoBehaviour
{
[SerializeField] private Card _parent = null!;
private void Awake()
{
_parent = transform.parent.GetComponent<Card>();
}
}
Does this not do what you want? I use the compiler flag #nullable enable and I’m able to use nullables in whatever code I want, pretty much. Your original example code also shows the other way to get rid of the warnings by using the ! symbol at the end of a name/identifier, which is essentially telling the compiler “I know what I’m doing here, it’ll be fine” and it just drops the issue and the warning is gone. I feel a little guilty for doing that sometimes and telling sweet Rosalyn to shut up, lol, but it’s honestly a pretty valid way to get rid of an unhelpful warning message you don’t need and when you’re fully aware of what’s going on and why she’s nervous.
Just try the flag I’ve mentioned above and demonstrated below and see if that isn’t exactly what you want/needed though …
using System;
using UnityEngine;
#nullable enable
public class Card : MonoBehaviour
{
[SerializeField] private Card? _parent = null;
private void Awake() {
_parent = transform.parent.GetComponent<Card>();
}
}
However, Unity C# is not compiled with nullable enabled, so all reference types are automatically nullable. Thus, with your own nullable enabled code, there are also null waring of methods that actually never return null. In addition, Unity also needs its own specific nullable settings that take into account Awake and Start. (And RequiredComponent attribute)
Of course not
private Card _parent = null! – It is just a way to suspend the erroneous warning for non-nullable field with the lack of constructor. And I hope that trick will be unnecessary in the future.
The situation with Unity right now is indeed not ideal, even if you enable it yourself for your own code.
Whilst semantically true right now, the plan for .NET is to move towards nullable reference types by default (in fact .NET 6 seems to have already enabled it by default), so Unity should follow suit at some point if they intend to keep up with .NET (which they seem to be working on), and having this in place sooner rather than later is beneficial as it allows gradual migration.
I just recently heard in a video on the dotnet channel on youtube, in .NET 7 the entire Framework now is compiled nullable enabled warning free. However, that only went with the help of the community due to the size of the framework.