Logo Tools Unity Navmesh

Tools Unity Navmesh

Cộng đồng
IdoCohen560
tools-unity-navmesh

Unity NavMesh pathfinding patterns, safety checks, and performance optimization.

Tổng quan

Nhà phát hànhIdoCohen560
Kho mãclaude-unity-game-studio
Tên kỹ năngtools-unity-navmesh
Sao
28
Bản fork
6
Tệp đi kèm
Chỉ có hướng dẫn
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Đầy đủ trong hướng dẫn

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được IdoCohen560 công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Tools Unity Navmesh trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/IdoCohen560/claude-unity-game-studio/tree/main/examples/my-first-game/.claude/skills/tools-unity-navmesh
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/IdoCohen560/claude-unity-game-studio.git /tmp/claude-unity-game-studio
mkdir -p .claude/skills
cp -r /tmp/claude-unity-game-studio/examples/my-first-game/.claude/skills/tools-unity-navmesh .claude/skills/tools-unity-navmesh
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Tools Unity Navmesh trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải Tools Unity Navmesh ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên Tools Unity Navmesh không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Unity NavMesh Pathfinding

Overview

NavMesh provides AI pathfinding in Unity. This skill covers safe usage patterns to prevent the 30K+ pathfinding errors seen in production.

When to Use

  • AI movement and navigation
  • Enemy patrolling and chasing
  • NPC pathfinding
  • Dynamic obstacle avoidance
  • Multi-agent navigation

Critical Safety Patterns

Graph Validation Before Query

csharp
using Pathfinding;

public class SafePathfinder
{
    private readonly Seeker _seeker;
    
    public bool TryCalculatePath(Vector3 start, Vector3 end, out Path path)
    {
        path = null;
        
        // CRITICAL: Check graph exists
        if (AstarPath.active == null)
        {
            Debug.LogError("No AstarPath instance active");
            return false;
        }
        
        if (AstarPath.active.graphs == null || AstarPath.active.graphs.Length == 0)
        {
            Debug.LogError("No graphs available");
            return false;
        }
        
        // Check if position is on navmesh
        var startNode = AstarPath.active.GetNearest(start).node;
        var endNode = AstarPath.active.GetNearest(end).node;
        
        if (startNode == null || !startNode.Walkable)
        {
            Debug.LogWarning($"Start position {start} not on walkable navmesh");
            return false;
        }
        
        if (endNode == null || !endNode.Walkable)
        {
            Debug.LogWarning($"End position {end} not on walkable navmesh");
            return false;
        }
        
        // Safe to calculate path
        _seeker.StartPath(start, end, OnPathComplete);
        return true;
    }
    
    private void OnPathComplete(Path p)
    {
        if (p.error)
        {
            Debug.LogWarning($"Path failed: {p.errorLog}");
            return;
        }
        
        // Use path
    }
}

Null Graph Guard (Critical Fix for 30K errors)

csharp
public class PathfindingGuard
{
    public static bool IsPathfindingReady()
    {
        // Check 1: AstarPath singleton exists
        if (AstarPath.active == null)
            return false;
        
        // Check 2: Data is loaded
        if (AstarPath.active.data == null)
            return false;
        
        // Check 3: Graphs exist
        if (AstarPath.active.data.graphs == null)
            return false;
        
        // Check 4: At least one graph is scanned
        foreach (var graph in AstarPath.active.data.graphs)
        {
            if (graph != null && graph.CountNodes() > 0)
                return true;
        }
        
        return false;
    }
}

// Usage in AI
public class EnemyAI : MonoBehaviour
{
    private void RequestPath()
    {
        if (!PathfindingGuard.IsPathfindingReady())
        {
            // Defer pathfinding or use fallback behavior
            StartCoroutine(WaitForPathfinding());
            return;
        }
        
        _seeker.StartPath(transform.position, _target.position);
    }
    
    private IEnumerator WaitForPathfinding()
    {
        while (!PathfindingGuard.IsPathfindingReady())
        {
            yield return new WaitForSeconds(0.5f);
        }
        
        RequestPath();
    }
}

NavMeshAgent Wrapper

csharp
public class SafeNavMeshAgent : MonoBehaviour
{
    private NavMeshAgent _agent;
    private bool _isNavigating;
    
    private void Awake()
    {
        _agent = GetComponent<NavMeshAgent>();
    }
    
    public bool TrySetDestination(Vector3 destination)
    {
        if (_agent == null || !_agent.isOnNavMesh)
        {
            Debug.LogWarning($"{name} not on NavMesh");
            return false;
        }
        
        // Check if destination is reachable
        NavMeshPath path = new NavMeshPath();
        if (!_agent.CalculatePath(destination, path))
        {
            Debug.LogWarning($"Cannot calculate path to {destination}");
            return false;
        }
        
        if (path.status != NavMeshPathStatus.PathComplete)
        {
            Debug.LogWarning($"Path incomplete: {path.status}");
            return false;
        }
        
        _agent.SetPath(path);
        _isNavigating = true;
        return true;
    }
    
    public void Stop()
    {
        if (_agent != null && _agent.isOnNavMesh)
        {
            _agent.isStopped = true;
            _agent.ResetPath();
        }
        _isNavigating = false;
    }
    
    private void OnDisable()
    {
        Stop();
    }
}

A* Pathfinding Project Patterns

Seeker Configuration

csharp
public class AIPathfinder : MonoBehaviour
{
    private Seeker _seeker;
    private AIPath _aiPath;
    
    private void Awake()
    {
        _seeker = GetComponent<Seeker>();
        _aiPath = GetComponent<AIPath>();
        
        // Configure seeker
        _seeker.pathCallback += OnPathComplete;
        
        // Set traversable tags
        _seeker.traversableTags = ~0; // All tags
    }
    
    private void OnDestroy()
    {
        if (_seeker != null)
        {
            _seeker.pathCallback -= OnPathComplete;
            _seeker.CancelCurrentPathRequest();
        }
    }
    
    public void MoveTo(Vector3 destination)
    {
        if (!PathfindingGuard.IsPathfindingReady())
        {
            Debug.LogWarning("Pathfinding not ready");
            return;
        }
        
        _aiPath.destination = destination;
        _aiPath.SearchPath();
    }
    
    private void OnPathComplete(Path p)
    {
        if (p.error)
        {
            HandlePathError(p);
            return;
        }
        
        // Path ready
    }
    
    private void HandlePathError(Path p)
    {
        Debug.LogWarning($"Path error: {p.errorLog}");
        
        // Fallback behavior - move directly or stay
    }
}

Path Caching

csharp
public class PathCache
{
    private readonly Dictionary<(Vector3Int, Vector3Int), Path> _cache = new();
    private readonly float _cacheValidTime = 5f;
    private readonly Dictionary<(Vector3Int, Vector3Int), float> _cacheTimestamps = new();
    
    private const float GridSize = 1f;
    
    public bool TryGetCachedPath(Vector3 start, Vector3 end, out Path path)
    {
        var key = (ToGridPos(start), ToGridPos(end));
        
        if (_cache.TryGetValue(key, out path))
        {
            if (_cacheTimestamps.TryGetValue(key, out var timestamp))
            {
                if (Time.time - timestamp < _cacheValidTime)
                {
                    return true;
                }
            }
            
            // Cache expired
            _cache.Remove(key);
            _cacheTimestamps.Remove(key);
        }
        
        path = null;
        return false;
    }
    
    public void CachePath(Vector3 start, Vector3 end, Path path)
    {
        var key = (ToGridPos(start), ToGridPos(end));
        _cache[key] = path;
        _cacheTimestamps[key] = Time.time;
    }
    
    private Vector3Int ToGridPos(Vector3 pos)
    {
        return new Vector3Int(
            Mathf.RoundToInt(pos.x / GridSize),
            Mathf.RoundToInt(pos.y / GridSize),
            Mathf.RoundToInt(pos.z / GridSize)
        );
    }
}

Performance Optimization

Batch Path Requests

csharp
public class PathBatcher
{
    private readonly Queue<PathRequest> _pendingRequests = new();
    private readonly int _maxRequestsPerFrame = 3;
    private bool _isProcessing;
    
    public void RequestPath(Vector3 start, Vector3 end, Action<Path> callback)
    {
        _pendingRequests.Enqueue(new PathRequest(start, end, callback));
        
        if (!_isProcessing)
        {
            ProcessBatch().Forget();
        }
    }
    
    private async UniTaskVoid ProcessBatch()
    {
        _isProcessing = true;
        
        while (_pendingRequests.Count > 0)
        {
            var processedThisFrame = 0;
            
            while (_pendingRequests.Count > 0 && processedThisFrame < _maxRequestsPerFrame)
            {
                var request = _pendingRequests.Dequeue();
                var path = await CalculatePathAsync(request.Start, request.End);
                request.Callback?.Invoke(path);
                processedThisFrame++;
            }
            
            await UniTask.Yield();
        }
        
        _isProcessing = false;
    }
    
    private async UniTask<Path> CalculatePathAsync(Vector3 start, Vector3 end)
    {
        var tcs = new UniTaskCompletionSource<Path>();
        
        var seeker = AstarPath.active.GetComponent<Seeker>();
        seeker.StartPath(start, end, p => tcs.TrySetResult(p));
        
        return await tcs.Task;
    }
    
    private readonly struct PathRequest
    {
        public readonly Vector3 Start;
        public readonly Vector3 End;
        public readonly Action<Path> Callback;
        
        public PathRequest(Vector3 start, Vector3 end, Action<Path> callback)
        {
            Start = start;
            End = end;
            Callback = callback;
        }
    }
}

LOD-Based Pathfinding

csharp
public class LODPathfinder
{
    private readonly float _preciseRadius = 20f;
    private readonly float _mediumRadius = 50f;
    
    public void RequestPath(Vector3 agent, Vector3 target)
    {
        var distance = Vector3.Distance(agent, target);
        
        if (distance <= _preciseRadius)
        {
            // Use full detail graph
            RequestPrecisePath(agent, target);
        }
        else if (distance <= _mediumRadius)
        {
            // Use simplified graph
            RequestMediumPath(agent, target);
        }
        else
        {
            // Use waypoint system
            RequestWaypointPath(agent, target);
        }
    }
}

Dynamic Obstacles

NavMesh Obstacle Handling

csharp
public class DynamicObstacle : MonoBehaviour
{
    private NavMeshObstacle _obstacle;
    private Coroutine _carveDelayCoroutine;
    
    private void Awake()
    {
        _obstacle = GetComponent<NavMeshObstacle>();
        _obstacle.carving = true;
        _obstacle.carveOnlyStationary = true;
    }
    
    public void EnableCarving()
    {
        if (_carveDelayCoroutine != null)
        {
            StopCoroutine(_carveDelayCoroutine);
        }
        
        // Delay carving to prevent rapid updates
        _carveDelayCoroutine = StartCoroutine(DelayedCarveEnable());
    }
    
    private IEnumerator DelayedCarveEnable()
    {
        yield return new WaitForSeconds(0.5f);
        _obstacle.carving = true;
    }
    
    public void DisableCarving()
    {
        if (_carveDelayCoroutine != null)
        {
            StopCoroutine(_carveDelayCoroutine);
        }
        _obstacle.carving = false;
    }
}

Graph Updates

csharp
public class NavMeshUpdater
{
    public void UpdateArea(Bounds bounds)
    {
        if (AstarPath.active == null) return;
        
        var graphUpdateObject = new GraphUpdateObject(bounds)
        {
            updatePhysics = true,
            modifyWalkability = true
        };
        
        AstarPath.active.UpdateGraphs(graphUpdateObject);
    }
    
    public void UpdateAreaAsync(Bounds bounds, Action onComplete)
    {
        if (AstarPath.active == null)
        {
            onComplete?.Invoke();
            return;
        }
        
        var graphUpdateObject = new GraphUpdateObject(bounds)
        {
            updatePhysics = true
        };
        
        AstarPath.active.UpdateGraphs(graphUpdateObject, onComplete);
    }
}

Error Recovery

Stuck Detection

csharp
public class StuckDetector : MonoBehaviour
{
    private Vector3 _lastPosition;
    private float _stuckTime;
    private const float StuckThreshold = 0.1f;
    private const float StuckTimeout = 3f;
    
    public event Action OnStuck;
    
    private void Update()
    {
        var moved = Vector3.Distance(transform.position, _lastPosition);
        
        if (moved < StuckThreshold)
        {
            _stuckTime += Time.deltaTime;
            
            if (_stuckTime >= StuckTimeout)
            {
                OnStuck?.Invoke();
                _stuckTime = 0f;
            }
        }
        else
        {
            _stuckTime = 0f;
        }
        
        _lastPosition = transform.position;
    }
}

Position Recovery

csharp
public class NavMeshRecovery
{
    public bool TryRecoverPosition(Transform agent, float searchRadius = 10f)
    {
        // Sample nearest valid position
        if (NavMesh.SamplePosition(agent.position, out var hit, searchRadius, NavMesh.AllAreas))
        {
            agent.position = hit.position;
            return true;
        }
        
        // Try expanding search
        for (float radius = searchRadius; radius <= 50f; radius += 10f)
        {
            if (NavMesh.SamplePosition(agent.position, out hit, radius, NavMesh.AllAreas))
            {
                agent.position = hit.position;
                return true;
            }
        }
        
        return false;
    }
}

Best Practices

  1. Always check graph validity before pathfinding
  2. Use path callbacks - Don't block on path calculation
  3. Batch path requests - Limit per-frame calculations
  4. Cache paths for repeated queries
  5. Handle path failures gracefully
  6. Use NavMesh.SamplePosition for validation
  7. Update graphs async for dynamic obstacles
  8. Implement stuck detection with recovery
  9. Cancel paths on disable/destroy
  10. Profile pathfinding cost on target devices

Troubleshooting

IssueSolution
NullReferenceException in pathfindingAdd graph null checks
Agent not movingCheck isOnNavMesh
Path incompleteVerify destination reachable
Slow pathfindingBatch requests, cache paths
Agent stuckImplement stuck detection + recovery
Dynamic obstacles ignoredEnable carving, update graphs

Câu hỏi thường gặp

Kỹ năng AI Tools Unity Navmesh làm được gì?

Unity NavMesh pathfinding patterns, safety checks, and performance optimization.

Vì sao nên dùng Tools Unity Navmesh trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Tools Unity Navmesh là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Tools Unity Navmesh trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/IdoCohen560/claude-unity-game-studio/tree/main/examples/my-first-game/.claude/skills/tools-unity-navmesh. TypingMind đọc tệp SKILL.md và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Tools Unity Navmesh?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng Tools Unity Navmesh với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Tools Unity Navmesh với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Tools Unity Navmesh có miễn phí không?

Có. Kỹ năng này được IdoCohen560 phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇