Which Unity types are nullable?

Viewed 2369

Why is it that putting

Renderer? myRenderer;

generates the error

The type 'Renderer' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>'

whereas

Vector3? myVector3;

does not?

By way of example, I want to be able to write

void ApplyMaterial(Material material)
{
    Renderer? renderer = targetDefinedExternally;
    renderer?.material = material;
}

In comparison, the following produces no errors

Vector3? vector;
float? magnitude = vector3?.magnitude;
vector3?.Normalize();

This suggests some Unity types are nullable whereas others aren't. How can I tell which is which? (And is there an elegant way to work around this?)

1 Answers

All types can be nullable.

A type is either a reference type or a value type. Reference types are nullable on their own. Value types are not nullable by default, and can be made nullable using the ? prefix.

Renderer is a class, which means it's a reference type. So you don't need the ? and it will work:

void ApplyMaterial(Material material)
{
    Renderer renderer = targetDefinedExternally;
}

Vector3 is a struct, which is a value type. This is why you can do:

Vector3? myVector3;

If your version of Unity supports C# 8, Renderer? would have worked too, since that is using the nullable reference type feature from C# 8.


That said, renderer?.material = material; won't work in either case, because the null conditional operator ?. can't be used in the LHS of an assignment :(

Related