Tools Unity Navmeshのロゴ

Tools Unity Navmesh

コミュニティ
IdoCohen560
tools-unity-navmesh

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

概要

公開者IdoCohen560
リポジトリclaude-unity-game-studio
スキル名tools-unity-navmesh
スター
28
フォーク
6
同梱ファイル
指示のみ
ライセンスMIT
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 指示だけで完結

    モデルに必要なものはすべて指示に含まれているため、別途同期するファイルはありません。

  • オープンソース

    IdoCohen560がGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキルTools Unity NavmeshをTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/IdoCohen560/claude-unity-game-studio/tree/main/examples/my-first-game/.claude/skills/tools-unity-navmesh
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをその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
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでTools Unity Navmeshを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあると、モデルが自動的にTools Unity Navmeshを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Tools Unity Navmeshは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、未使用のスキルにはコストがかかりません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

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

よくある質問

AIスキル「Tools Unity Navmesh」では何ができますか?

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

TypingMindでTools Unity Navmeshを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Tools Unity Navmeshはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにTools Unity Navmeshをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/IdoCohen560/claude-unity-game-studio/tree/main/examples/my-first-game/.claude/skills/tools-unity-navmeshを貼り付けてください。TypingMindがSKILL.mdを読み込み、チャットごとに有効にできるスキルとしてインストールします。

Tools Unity Navmeshを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストが合致したときにこのスキルを読み込めます。

Tools Unity Navmeshは何個のAIモデルで使えますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもTools Unity Navmeshを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Tools Unity Navmesh」は無料ですか?

はい。IdoCohen560がGitHubでMITライセンスの下で公開しています。支払いが必要なのは、利用したトークンに対する、ご自身が契約するAIプロバイダーへの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇