Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ///<summary>
- ///
- /// This class is used for dungeons or terrain(not tested)
- /// once the scene is ready and the NavMesh as been baked, will activate all NPCs
- /// via AIManager
- ///
- /// ADD THIS COMPONENT TO A PARENT THAT INCLUDE ALL WALKABLE SURFACE
- ///
- ///</summary>
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.AI;
- [RequireComponent(typeof(AiManager))]
- public class NavMeshBaker : MonoBehaviour
- {
- [SerializeField] bool OnStart = false;
- [SerializeField] bool debugBounds = false;
- [Space]
- [SerializeField] List<NavMeshSurface> navMeshSurfaces = new List<NavMeshSurface>();
- NavMeshBuildSettings set = NavMesh.CreateSettings();
- private void Start()
- {
- if (OnStart)
- BakeNavMesh();
- }
- /// <summary>
- /// It will store all tiles with a NavMeshSurface and generate the NavMesh, then will awake all NPCs
- /// </summary>
- public void BakeNavMesh()
- {
- // Add all floors the array
- navMeshSurfaces = new List<NavMeshSurface>(GetComponentsInChildren<NavMeshSurface>());
- NavMeshData built = NavMeshBuilder.BuildNavMeshData(set,Nav2Nav(navMeshSurfaces), CalculateLocalBounds(), transform.position, transform.rotation);
- NavMesh.AddNavMeshData(built);
- GetComponent<AiManager>().EnableEnemies();
- }
- private List<NavMeshBuildSource> Nav2Nav(List<NavMeshSurface> array)
- {
- List<NavMeshBuildSource> nmBuildSource = new List<NavMeshBuildSource>();
- foreach (var tile in array)
- {
- NavMeshBuildSource floor = new NavMeshBuildSource();
- floor.transform = tile.transform.localToWorldMatrix;
- floor.shape = NavMeshBuildSourceShape.Box;
- floor.size = tile.GetComponent<Renderer>().bounds.size;
- nmBuildSource.Add(floor);
- }
- return nmBuildSource;
- }
- private Bounds CalculateLocalBounds()
- {
- navMeshSurfaces.Clear();
- navMeshSurfaces = new List<NavMeshSurface>(GetComponentsInChildren<NavMeshSurface>());
- Bounds bounds = new Bounds(this.transform.position, Vector3.zero);
- foreach (var floor in navMeshSurfaces)
- {
- bounds.Encapsulate(floor.GetComponent<Renderer>().bounds);
- }
- Vector3 localCenter = bounds.center - this.transform.localPosition;
- bounds.center = localCenter;
- Debug.Log("The local bounds of this model is " + bounds);
- return bounds;
- }
- void OnDrawGizmosSelected()
- {
- BakeNavMesh();
- if (debugBounds)
- {
- Bounds bounds = CalculateLocalBounds();
- Debug.Log("Selected obj " + bounds);
- Gizmos.color = new Color(1, 1, 1, 0.25f);
- Gizmos.DrawCube(bounds.center, bounds.size);
- Gizmos.DrawWireCube(bounds.center, bounds.size);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement