terminalCode Example

Prefab Spawning and Cloning

calendar_today May 3, 2026 schedule ~1 min read person patrickjr verified 50

Prefab Spawning and Cloning

Prefabs are reusable GameObject templates that can be instantiated at runtime.

Creating Prefabs

  1. Create a GameObject in the scene with all desired components
  2. Right-click → Convert to Prefab
  3. The GameObject turns blue, indicating it's linked to a prefab

Spawning Prefabs in Code

CSHARP
public sealed class MyGun : Component
{
    [Property] 
    public GameObject BulletPrefab { get; set; }

    protected override void OnUpdate()
    {
        // Validate the prefab is set in the inspector
        Assert.NotNull(BulletPrefab);
        
        if (Input.Pressed("Attack1"))
        {
            // Clone the prefab at the gun's position
            GameObject bullet = BulletPrefab.Clone(WorldPosition);
            
            // Get a component on the cloned object
            var rb = bullet.Components.Get<Rigidbody>();
            if (rb != null)
            {
                rb.Velocity = WorldRotation.Forward * 1000f;
            }
        }
    }
}

Prefab Lifecycle

Clone vs BreakFromPrefab

CSHARP
// Spawn a prefab instance
GameObject instance = myPrefab.Clone(position);

// The instance is linked to the prefab - editor changes update all instances
// To make it independent:
instance.BreakFromPrefab();
// Now it appears as normal GameObjects in the hierarchy

PrefabFile Assets

Prefabs are saved as .prefab assets that can be referenced like GameObjects:

CSHARP
[Property]
public PrefabFile WeaponPrefab { get; set; }

public void SpawnWeapon()
{
    if (WeaponPrefab == null) return;
    
    // Load and instantiate
    var weapon = WeaponPrefab.Clone(spawnPoint);
}

Instance Overrides

Prefab instances can have local overrides for properties. See Instance Overridesopen_in_new for details on modifying specific instances while keeping the prefab link.

Was this helpful?