using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.AI; using UnityEngine.Rendering; using UnityEngine.Serialization; namespace RPGCore.SceneModules.PathVisualizerSceneModule { public class PathVisualizer : MonoBehaviour { private Func> _pathGetter; private LineRenderer _lineRenderer; private float _autoUpdateDelta; public bool autoUpdate; public float autoUpdateTime; public float verticalOffset; public float lineSize { get => _lineRenderer.startWidth; set => _lineRenderer.startWidth = _lineRenderer.endWidth = value; } public Material material { get => _lineRenderer.material; set => _lineRenderer.material = value; } public void SetPath(Vector3 start, Vector3 end, int navMeshAreaMask) { var path = new NavMeshPath(); NavMesh.CalculatePath(start, end, navMeshAreaMask, path); _pathGetter = () => path.corners; UpdatePath(); } public void SetPath(NavMeshAgent agent, Vector3 destination) { var path = new NavMeshPath(); agent.CalculatePath(destination, path); _pathGetter = () => path.corners; UpdatePath(); } public void SetPath(NavMeshPath path) { _pathGetter = () => path.corners; UpdatePath(); } public void SetPath(IEnumerable customPath) { _pathGetter = () => customPath.Select(t => t.position); UpdatePath(); } public void SetPath(IEnumerable customPath) { _pathGetter = () => customPath; UpdatePath(); } public void SetPath(Func> pathGetter) { _pathGetter = pathGetter; UpdatePath(); } private void Awake() { _lineRenderer = gameObject.AddComponent(); _lineRenderer.enabled = true; _lineRenderer.shadowCastingMode = ShadowCastingMode.Off; _lineRenderer.numCapVertices = 3; _lineRenderer.numCornerVertices = 3; } private void FixedUpdate() { if (!autoUpdate) return; _autoUpdateDelta += Time.fixedDeltaTime; if (_autoUpdateDelta < autoUpdateTime) return; _autoUpdateDelta = 0; UpdatePath(); } private void UpdatePath() { if (_pathGetter == null) return; var path = _pathGetter().Select(pos => pos + Vector3.up * verticalOffset).ToArray(); _lineRenderer.positionCount = path.Length; _lineRenderer.SetPositions(path); } public void Show() { _lineRenderer.enabled = true; } public void Hide() { _lineRenderer.enabled = false; } } }