I’m trying to create an object that can have a destination, but may also not have a destination. So I created a Vector2? moveDestination field in my class.
public class Resource: MonoBehaviour
{
// Configuration
public float speed = 1.0f;
// State
private Vector2? moveDestination = null;
public void Update() {
if (moveDestination != null) {
Vector2 nonNullMoveDestination = moveDestination;
float distance = speed * Time.deltaTime;
Vector2 newPosition = Vector2.MoveTowards(transform.position, nonNullMoveDestination, distance);
}
}
}
I get a CS0266 error stating that it can’t auto convert from Vector2? to Vector2. But as far as I understand, the null check should have caused an auto conversion.
There might even be a bug report for this on Unity: https://issuetracker.unity3d.com/issues/error-cs0266-when-using-implicit-operator-to-convert-nullable-struct-to-non-nullable (hard to check, as that bug report uses an attached script that I cannot download).
One solution is to do:
Vector2 nonNullMoveDestination = (Vector2)moveDestination;
But I’m wondering what is the idiomatic C# / Unity way to deal with this situation.
(Note, my background is Kotlin, so I’ve grown rather accustomed to auto-conversion, and would love to also have this in C#/Unity.)