In this lesson, you will learn how to use Prefab Variants to create unique versions of a base object without duplicating your original assets or breaking their core logic.
The Concept of Inheritance
When building games, you often have items that share the same behavior but look slightly different. For example, imagine you have a BaseSword prefab with a specific damage script and sound effects. If you want a FireSword and an IceSword, you don't need to rebuild them from scratch.
A Prefab Variant acts like a child class in programming. It inherits everything from the "Base" prefab. If you change a value in the Base (like increasing the base attack speed), that change automatically updates all your variants. However, you can also "override" specific properties in the variant—like changing the material color or the particle effect—without affecting the original.
How to Create a Variant
Creating a variant is simple and keeps your project organized:
- Locate your base Prefab in your Project window.
- Right-click the Prefab and select Create > Prefab Variant.
- A new Prefab icon will appear with a distinct "blue lines" symbol, indicating it is a child of the original.
- Drag this variant into your scene and make your specific changes (like swapping the Mesh Renderer material).
When you make these changes, the Inspector will highlight the modified properties in bold, signifying an override.
// Example Logic: Both base and variant use this script
public class Weapon : MonoBehaviour {
public float damage = 10f;
public ParticleSystem hitEffect;
void OnCollisionEnter() {
// Shared logic: play the assigned hitEffect
hitEffect.Play();
}
}
By using variants, you keep your game architecture clean. The Weapon script remains attached to the base prefab, meaning any future improvements you make to that script will automatically propagate to all your specialized swords, ensuring your game remains easy to balance and update as your project grows.
Key Takeaway: Prefab Variants allow you to maintain a single source of truth for functionality while enabling flexible visual or property-based customization across your asset library.