SpawnOnBake (Sample Script)
Provided as a part of the Samples
Last updated
using MegaCrush.RuntimeNavmeshBaker;
using UnityEngine;
using UnityEngine.AI;
namespace MegaCrush.NavmeshBaker.Sample
{
/// <summary>
/// Spawns a prefab after the first completed runtime bake.
/// Listens to BakerEvents instead of directly binding to the service.
/// </summary>
public sealed class SpawnOnBake : MonoBehaviour
{
[Header("Prefab to Spawn")]
[SerializeField] private GameObject prefab;
[Header("Spawn Settings")]
[SerializeField] private Transform spawnPoint;
[SerializeField] private bool onlyOnce = true;
[Header("NavMesh Sampling")]
[SerializeField, Min(0f)] private float sampleMaxDistance = 5f;
[SerializeField] private int areaMask = NavMesh.AllAreas;
private bool _hasSpawned;
private void OnEnable()
{
BakerEvents.OnBakeCompleted += HandleBakeCompleted;
}
private void OnDisable()
{
BakerEvents.OnBakeCompleted -= HandleBakeCompleted;
}
private void HandleBakeCompleted(DynamicNavMeshSurface surface, Bounds region, float durationSeconds)
{
if (!prefab) return;
if (onlyOnce && _hasSpawned) return;
Vector3 desired = spawnPoint ? spawnPoint.position : transform.position;
if (NavMesh.SamplePosition(desired, out NavMeshHit hit, sampleMaxDistance, areaMask))
{
Instantiate(prefab, hit.position, Quaternion.identity);
_hasSpawned = true;
#if UNITY_EDITOR
Debug.Log($"[SpawnOnBake] Spawned '{prefab.name}' at {hit.position} (region {region.center}±{region.extents})");
#endif
}
else
{
#if UNITY_EDITOR
Debug.LogWarning($"[SpawnOnBake] No valid NavMesh within {sampleMaxDistance}m of {desired}. " +
"Increase Sample Max Distance or adjust Spawn Point.");
#endif
}
}
}
}