Course contentsShow
← Unity Game Development
Lesson 298 of 8284. Prefabs and Data ManagementFree lesson

Handling Polymorphic Data with SerializeReference

Learners will use the [SerializeReference] attribute to store and serialize varying class types while maintaining proper object references in the inspector.

In this lesson, you will learn how to use [SerializeReference] to store different subclasses within a single list or variable while keeping them fully editable in the Unity Inspector.

The Challenge of Polymorphism

Unity’s default serialization system struggles with polymorphism. If you have an abstract base class like EnemyAbility and two subclasses, Fireball and Heal, a standard List<EnemyAbility> will often "strip" the extra data from your subclasses when you look at them in the Inspector. It treats them as the base type, making your unique data disappear.

Enter [SerializeReference]

The [SerializeReference] attribute tells Unity to treat the field as a polymorphic reference. Instead of trying to serialize the object "inline," Unity stores the specific type information and preserves the object’s full structure.

Here is how you implement it:

using UnityEngine;
using System;
using System.Collections.Generic;

[Serializable]
public abstract class EnemyAbility { public float cooldown; }

[Serializable]
public class Fireball : EnemyAbility { public int damage; }

[Serializable]
public class Heal : EnemyAbility { public int healAmount; }

public class AbilityManager : MonoBehaviour
{
    // The attribute enables the dropdown in the inspector
    [SerializeReference] 
    public List<EnemyAbility> abilities = new List<EnemyAbility>();
}

Why This Matters

When you apply this attribute, Unity updates the Inspector to show a "Type" dropdown for each element in your list. You can select Fireball or Heal directly from the UI, and Unity will correctly instantiate and serialize the specific class you chose.

This is incredibly powerful for designers. You can build complex, data-driven systems—like item effects, skill trees, or AI behavior trees—without writing custom inspectors for every single permutation of your data. You maintain a clean architecture in your code while granting designers the flexibility to swap and configure different behaviors on the fly.

Key Takeaway: Use [SerializeReference] when you need to store a collection of different object types in the Inspector, as it preserves class-specific data that Unity’s default serialization would otherwise discard.