Skip to main content

ComponentTypeSelector

Change a component's class right in the Inspector while shared fields keep their values.

Quick start​

public abstract class EnemyBase : MonoBehaviour
{
[SerializeField] private ComponentTypeSelector _enemyType;
[SerializeField] private float _health = 100f;
}
FastEnemy.csArmoredEnemy.cs
public sealed class FastEnemy : EnemyBase
{
[SerializeField]
private float _speed = 25f;
}
public sealed class ArmoredEnemy : EnemyBase
{
[SerializeField]
private int _armor = 10;
}

The list offers the class that declares the field, unless it is abstract, and its concrete subclasses, with no <None> entry. Display settings from [TypeSelectorDisplay] apply here, while [TypeSelector] does not configure the list.

Picking ArmoredEnemy instead of FastEnemy keeps Health = 75Picking ArmoredEnemy instead of FastEnemy keeps Health = 75

FieldFastEnemyArmoredEnemy pickedBack to FastEnemy
Health757575
Speed40—25
Armor—10—

When the type does not change​

The switch follows the rules of Add Component: the components the new class lists in [RequireComponent] are added with it. The class stays as it was, and the Console shows why, when:

  • Unity would refuse to add the new class or remove the old one;
  • the class has no script file of its own with the same name, such as a nested class;
  • the component is inherited from a prefab (an instance in a scene or a variant): change its class in the source prefab.

With several components selected, a refusal for one of them leaves all of them as they were.

Package sample​

The Types sample shows component type switching.

A wave of regular and elite enemies in the Types sceneA wave of regular and elite enemies in the Types scene