terminalCode Example
Prefab Spawning and Cloning
Prefab Spawning and Cloning
Prefabs are reusable GameObject templates that can be instantiated at runtime.
Creating Prefabs
- Create a GameObject in the scene with all desired components
- Right-click → Convert to Prefab
- 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 hierarchyPrefabFile 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 Overrides for details on modifying specific instances while keeping the prefab link.
Was this helpful?