🤔 Unity, huh, how?

🤔

NullReferenceException: Plain C# objects

To resolve a NullReferenceException caused by plain C# objects make sure you've assigned a value, and either don't unassign it, or check that's the case.

1. Assign a value (choose one)

2. Check for null, or ensure null is never assigned

Ensure nothing assigns null to the reference before you access it.

Or:

Check the reference isn't null before you access it (choose one)

  • Exit early if null:
    if (example == null)
    {
        // Exit early.
        return;
    }
    // Code that uses example.
  • Nest your code in a null check:
    if (example != null)
    {
        // Code that uses example.
    }
  • Use a null conditional operator:
    example?.Do(); // Example of null-conditional member access.