mohumohu studio みずきの技術&読書ブログ&無料ゲーム

mohumohu studio

           

みずきの技術&読書ブログ&無料ゲーム

プロフィール画像

【C# / Unity】What Is a NullReferenceException? Causes and Solutions Explained for Beginners

If you develop with C# or Unity, there is one error you will almost certainly encounter at least once:

NullReferenceException

You may have experienced situations like:

  • “It worked yesterday, but now it suddenly crashes.”
  • “I don’t understand what this error message means.”
  • “I have no idea where I should fix the code.”

When I first started using Unity, this error caused me a lot of frustration as well.
However, once you understand how and why it happens, NullReferenceException is no longer something to fear.

In this article, you will learn:

  • What a NullReferenceException is
  • Why it happens
  • Common causes and how to fix them
  • How to prevent it through better design

All explained in a beginner-friendly way, especially for Unity developers.


Table of Contents

  1. What Is a NullReferenceException?
  2. :Common Causes of NullReferenceException
    1. GetComponent Fails to Find the Component
    2. Forgot to Assign a Reference in the Inspector
    3. Using a Class Without Creating an Instance
    4. Null Elements Inside Arrays or Lists
  3. How to Read Unity Error Logs Correctly
  4. Basic Debugging Techniques
    1. Use Debug.Log to Check for null
    2. Guard Your Code with if Statements
  5. How to Prevent NullReferenceException Through Design
    1. Always Initialize in Awake or Start
    2. Use SerializeField Instead of public
    3. Always Ask: “Can This Be Null?”
  6. Summary

What Is a NullReferenceException?

A NullReferenceException occurs when:

You try to access an object reference that is null

In simple terms, you are trying to use something that does not exist.

For example:


GameObject player = null;
player.SetActive(true);


Here, player is null, but the code tries to call SetActive() on it.
This results in a NullReferenceException.

In other words, the error happens when you try to use:

  • An object that hasn’t been created
  • A reference that was never assigned

Common Causes of NullReferenceException

① GetComponent Fails to Find the Component


Enemy enemy = GetComponent<Enemy>();
enemy.Damage(10);

This error occurs if:

  • The Enemy component is not attached to the GameObject
  • The component exists on a different GameObject

In these cases, enemy will be null.

👉 This is the most common mistake for Unity beginners.


② Forgot to Assign a Reference in the Inspector


public GameObject effect;

void Start()
{
    effect.SetActive(true);
}

If effect is not assigned in the Inspector, it remains null.

Common scenarios include:

  • You added a variable but forgot to assign it
  • It is assigned in the prefab but not in the scene object

This is another very frequent cause.


③ Using a Class Without Creating an Instance


PlayerStatus status;

void Start()
{
    Debug.Log(status.hp);
}

Here, status is declared but never instantiated.

You must create it first:


status = new PlayerStatus();

If you forget this, a NullReferenceException will always occur.


④ Null Elements Inside Arrays or Lists


List<Enemy> enemies = new List<Enemy>();

void Update()
{
    enemies[0].Attack();
}

Possible issues include:

  • No elements were added to the list
  • An element was removed earlier

Even if the list exists, its contents can still be null.


How to Read Unity Error Logs Correctly

Unity’s Console always provides important clues.

Example:


NullReferenceException: Object reference not set to an instance of an object
Player.Attack() (at Assets/Scripts/Player.cs:42)

Pay attention to:

  • Player.cs
  • Line 42

👉 This line is where you should start looking for variables that might be null.


Basic Debugging Techniques

Use Debug.Log to Check for null


if (enemy == null)
{
    Debug.Log("enemy is null");
}

Logging makes it much easier to identify where the reference becomes null.


Guard Your Code with if Statements


if (enemy != null)
{
    enemy.Damage(10);
}

This is a valid temporary solution.

However, always ask yourself:

  • Why is it null?
  • Should it ever be null in the first place?

How to Prevent NullReferenceException Through Design

① Always Initialize in Awake or Start


void Awake()
{
    enemy = GetComponent<Enemy>();
}

Make it a habit to check:

  • Is the variable assigned before use?
  • Is the initialization timing correct?

This alone can drastically reduce errors.


② Use SerializeField Instead of public


[SerializeField]
private GameObject effect;

Benefits:

  • Keeps variables private
  • Still allows assignment in the Inspector
  • Leads to cleaner design

👉 Highly recommended in Unity projects.


③ Always Ask: “Can This Be Null?”

Experienced developers constantly think:

“Is there any chance this variable could be null?”

Every time you encounter a NullReferenceException, treat it as a chance to improve your design—not just a bug to fix.


Summary

  • NullReferenceException is a rite of passage for C# and Unity developers
  • Most cases are caused by:
    • Failed GetComponent calls
    • Forgotten Inspector assignments
    • Missing initialization
  • Always check the file name and line number in the error log
  • Designing your code with null safety in mind greatly improves development efficiency
2026-01-05

0件のコメント

コメントはまだありません。最初の一人になりましょう!

Leave a Reply

Your email address will not be published. Required fields are marked *