Tools Unity Behavior Designer 标志

Tools Unity Behavior Designer

社区
IdoCohen560
tools-unity-behavior-designer

Behavior Designer patterns for AI behavior trees including task creation, shared variables, conditionals, and debugging.

概览

发布者IdoCohen560
代码仓库claude-unity-game-studio
技能名称tools-unity-behavior-designer
星标数
28
复刻数
6
附带文件
仅含指令
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 IdoCohen560 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Tools Unity Behavior Designer AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

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-behavior-designer
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

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-behavior-designer .claude/skills/tools-unity-behavior-designer
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Tools Unity Behavior Designer,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Tools Unity Behavior Designer。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Tools Unity Behavior Designer 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Behavior Designer

Overview

Behavior Designer is a behavior tree implementation for Unity AI. This skill covers patterns for creating robust AI behaviors for enemies, NPCs, and game entities.

When to Use

  • Enemy AI behavior
  • NPC decision making
  • Boss fight patterns
  • Companion AI
  • Any complex state-based AI

Core Concepts

Behavior Tree Structure

Selector (OR logic - first success wins)
├── Sequence (AND logic - all must succeed)
│   ├── Conditional (check condition)
│   └── Action (do something)
├── Sequence
│   ├── Conditional
│   └── Action
└── Action (fallback)

Custom Tasks

Action Task

csharp
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;

[TaskCategory("Combat")]
[TaskDescription("Attacks the current target")]
public class AttackTarget : Action
{
    [Tooltip("Reference to the ability system")]
    public SharedGameObject abilitySystemOwner;
    
    [Tooltip("The ability to activate")]
    public SharedString abilityTag;
    
    [Tooltip("Target to attack")]
    public SharedGameObject target;
    
    private IAbilitySystem _abilitySystem;
    private bool _abilityStarted;
    
    public override void OnStart()
    {
        _abilityStarted = false;
        
        if (abilitySystemOwner.Value == null)
        {
            Debug.LogError("AttackTarget: No ability system owner");
            return;
        }
        
        _abilitySystem = abilitySystemOwner.Value.GetComponent<IAbilitySystem>();
    }
    
    public override TaskStatus OnUpdate()
    {
        if (_abilitySystem == null || target.Value == null)
        {
            return TaskStatus.Failure;
        }
        
        if (!_abilityStarted)
        {
            if (!_abilitySystem.TryActivateAbilityByTag(abilityTag.Value))
            {
                return TaskStatus.Failure;
            }
            _abilityStarted = true;
        }
        
        // Check if ability is still running
        if (_abilitySystem.IsAbilityActive(abilityTag.Value))
        {
            return TaskStatus.Running;
        }
        
        return TaskStatus.Success;
    }
    
    public override void OnEnd()
    {
        // Cleanup if interrupted
        if (_abilityStarted && _abilitySystem != null)
        {
            _abilitySystem.CancelAbilityByTag(abilityTag.Value);
        }
    }
}

Conditional Task

csharp
[TaskCategory("Combat")]
[TaskDescription("Checks if target is within attack range")]
public class IsTargetInRange : Conditional
{
    public SharedGameObject target;
    public SharedFloat attackRange;
    public SharedTransform selfTransform;
    
    public override TaskStatus OnUpdate()
    {
        if (target.Value == null || selfTransform.Value == null)
        {
            return TaskStatus.Failure;
        }
        
        float distance = Vector3.Distance(
            selfTransform.Value.position,
            target.Value.transform.position
        );
        
        return distance <= attackRange.Value 
            ? TaskStatus.Success 
            : TaskStatus.Failure;
    }
}

Composite Task (Custom Selector)

csharp
[TaskCategory("Custom")]
[TaskDescription("Weighted random selection of children")]
public class WeightedSelector : Composite
{
    [Tooltip("Weights for each child (must match child count)")]
    public float[] weights;
    
    private int _currentChildIndex = -1;
    private int _executedChildIndex = -1;
    
    public override void OnStart()
    {
        _currentChildIndex = SelectWeightedChild();
        _executedChildIndex = -1;
    }
    
    public override int CurrentChildIndex()
    {
        return _currentChildIndex;
    }
    
    public override bool CanExecute()
    {
        return _currentChildIndex != _executedChildIndex 
            && _currentChildIndex < children.Count;
    }
    
    public override void OnChildExecuted(TaskStatus childStatus)
    {
        _executedChildIndex = _currentChildIndex;
    }
    
    public override void OnConditionalAbort(int childIndex)
    {
        _currentChildIndex = childIndex;
        _executedChildIndex = childIndex - 1;
    }
    
    private int SelectWeightedChild()
    {
        if (weights == null || weights.Length == 0)
        {
            return Random.Range(0, children.Count);
        }
        
        float totalWeight = 0f;
        for (int i = 0; i < Mathf.Min(weights.Length, children.Count); i++)
        {
            totalWeight += weights[i];
        }
        
        float randomValue = Random.Range(0f, totalWeight);
        float currentWeight = 0f;
        
        for (int i = 0; i < Mathf.Min(weights.Length, children.Count); i++)
        {
            currentWeight += weights[i];
            if (randomValue <= currentWeight)
            {
                return i;
            }
        }
        
        return 0;
    }
}

Decorator Task

csharp
[TaskCategory("Decorators")]
[TaskDescription("Repeats child until condition is false")]
public class RepeatWhile : Decorator
{
    public SharedBool condition;
    
    private TaskStatus _childStatus = TaskStatus.Inactive;
    
    public override bool CanExecute()
    {
        return condition.Value && _childStatus != TaskStatus.Running;
    }
    
    public override void OnChildExecuted(TaskStatus childStatus)
    {
        _childStatus = childStatus;
    }
    
    public override TaskStatus Decorate(TaskStatus status)
    {
        if (!condition.Value)
        {
            return TaskStatus.Success;
        }
        
        return TaskStatus.Running;
    }
    
    public override void OnEnd()
    {
        _childStatus = TaskStatus.Inactive;
    }
}

Shared Variables

Defining Shared Variables

csharp
// In your behavior tree component or global variables
public class EnemyBehaviorVariables : MonoBehaviour
{
    [Header("References")]
    public SharedGameObject self;
    public SharedTransform selfTransform;
    public SharedGameObject currentTarget;
    
    [Header("Combat")]
    public SharedFloat attackRange = 2f;
    public SharedFloat detectionRange = 10f;
    public SharedFloat health;
    public SharedBool isInCombat;
    
    [Header("Movement")]
    public SharedVector3 homePosition;
    public SharedVector3 targetPosition;
    public SharedFloat moveSpeed = 5f;
}

Custom Shared Variable Type

csharp
[Serializable]
public class SharedAbilityData : SharedVariable<AbilityData>
{
    public static implicit operator SharedAbilityData(AbilityData value)
    {
        return new SharedAbilityData { Value = value };
    }
}

// Usage in task
public class UseAbility : Action
{
    public SharedAbilityData ability;
    
    public override TaskStatus OnUpdate()
    {
        if (ability.Value == null)
            return TaskStatus.Failure;
            
        // Use ability data
        return TaskStatus.Success;
    }
}

Global Variables

csharp
public class AIGlobalVariables : MonoBehaviour
{
    public static AIGlobalVariables Instance { get; private set; }
    
    private GlobalVariables _globalVariables;
    
    private void Awake()
    {
        Instance = this;
        _globalVariables = GlobalVariables.Instance;
    }
    
    public void SetPlayerReference(GameObject player)
    {
        _globalVariables.SetVariable("Player", (SharedGameObject)player);
    }
    
    public void SetCombatState(bool inCombat)
    {
        _globalVariables.SetVariable("GlobalCombatActive", (SharedBool)inCombat);
    }
    
    public GameObject GetPlayer()
    {
        var playerVar = _globalVariables.GetVariable("Player") as SharedGameObject;
        return playerVar?.Value;
    }
}

Common Patterns

Target Selection

csharp
[TaskCategory("Targeting")]
public class FindClosestEnemy : Action
{
    public SharedGameObject result;
    public SharedFloat searchRadius;
    public SharedLayerMask targetLayers;
    public SharedTransform selfTransform;
    
    private Collider[] _hitColliders = new Collider[20];
    
    public override TaskStatus OnUpdate()
    {
        if (selfTransform.Value == null)
            return TaskStatus.Failure;
        
        int hitCount = Physics.OverlapSphereNonAlloc(
            selfTransform.Value.position,
            searchRadius.Value,
            _hitColliders,
            targetLayers.Value
        );
        
        if (hitCount == 0)
        {
            result.Value = null;
            return TaskStatus.Failure;
        }
        
        float closestDistance = float.MaxValue;
        GameObject closest = null;
        
        for (int i = 0; i < hitCount; i++)
        {
            var col = _hitColliders[i];
            if (col.gameObject == selfTransform.Value.gameObject)
                continue;
            
            float dist = Vector3.Distance(
                selfTransform.Value.position,
                col.transform.position
            );
            
            if (dist < closestDistance)
            {
                closestDistance = dist;
                closest = col.gameObject;
            }
        }
        
        result.Value = closest;
        return closest != null ? TaskStatus.Success : TaskStatus.Failure;
    }
}

Movement Tasks

csharp
[TaskCategory("Movement")]
public class MoveToTarget : Action
{
    public SharedGameObject target;
    public SharedFloat stoppingDistance = 1f;
    public SharedFloat moveSpeed = 5f;
    
    private IAstarAI _ai;
    private Transform _transform;
    
    public override void OnStart()
    {
        _ai = GetComponent<IAstarAI>();
        _transform = transform;
    }
    
    public override TaskStatus OnUpdate()
    {
        if (target.Value == null)
            return TaskStatus.Failure;
        
        if (_ai != null)
        {
            _ai.destination = target.Value.transform.position;
            
            if (_ai.reachedEndOfPath)
                return TaskStatus.Success;
                
            return TaskStatus.Running;
        }
        
        // Fallback simple movement
        Vector3 direction = (target.Value.transform.position - _transform.position).normalized;
        _transform.position += direction * moveSpeed.Value * Time.deltaTime;
        
        float distance = Vector3.Distance(
            _transform.position,
            target.Value.transform.position
        );
        
        return distance <= stoppingDistance.Value 
            ? TaskStatus.Success 
            : TaskStatus.Running;
    }
    
    public override void OnEnd()
    {
        if (_ai != null)
        {
            _ai.isStopped = true;
        }
    }
}

Patrol Pattern

csharp
[TaskCategory("Movement")]
public class Patrol : Action
{
    public SharedTransformList waypoints;
    public SharedInt currentWaypointIndex;
    public SharedFloat waypointReachedDistance = 1f;
    
    private IAstarAI _ai;
    
    public override void OnStart()
    {
        _ai = GetComponent<IAstarAI>();
        
        if (waypoints.Value == null || waypoints.Value.Count == 0)
        {
            return;
        }
        
        SetDestinationToCurrentWaypoint();
    }
    
    public override TaskStatus OnUpdate()
    {
        if (waypoints.Value == null || waypoints.Value.Count == 0)
            return TaskStatus.Failure;
        
        if (_ai == null)
            return TaskStatus.Failure;
        
        // Check if reached waypoint
        float distance = Vector3.Distance(
            transform.position,
            waypoints.Value[currentWaypointIndex.Value].position
        );
        
        if (distance <= waypointReachedDistance.Value)
        {
            // Move to next waypoint
            currentWaypointIndex.Value = 
                (currentWaypointIndex.Value + 1) % waypoints.Value.Count;
            SetDestinationToCurrentWaypoint();
        }
        
        return TaskStatus.Running;
    }
    
    private void SetDestinationToCurrentWaypoint()
    {
        if (_ai != null && waypoints.Value.Count > currentWaypointIndex.Value)
        {
            _ai.destination = waypoints.Value[currentWaypointIndex.Value].position;
            _ai.isStopped = false;
        }
    }
}

Combat State Machine

csharp
// Tree structure for combat AI
/*
Selector (Root)
├── Sequence [Flee when low health]
│   ├── IsHealthLow
│   └── FleeFromTarget
├── Sequence [Attack when in range]
│   ├── HasTarget
│   ├── IsTargetInRange
│   └── Selector [Choose attack]
│       ├── Sequence [Special attack if ready]
│       │   ├── IsSpecialReady
│       │   └── UseSpecialAttack
│       └── UseBasicAttack
├── Sequence [Chase target]
│   ├── HasTarget
│   └── MoveToTarget
└── Patrol [Default behavior]
*/

[TaskCategory("Combat")]
public class IsHealthLow : Conditional
{
    public SharedFloat currentHealth;
    public SharedFloat maxHealth;
    public SharedFloat lowHealthThreshold = 0.2f;
    
    public override TaskStatus OnUpdate()
    {
        float healthPercent = currentHealth.Value / maxHealth.Value;
        return healthPercent <= lowHealthThreshold.Value 
            ? TaskStatus.Success 
            : TaskStatus.Failure;
    }
}

Conditional Aborts

Self Abort Pattern

csharp
// Use AbortType.Self to re-evaluate when conditions change
[TaskCategory("Combat")]
public class HasTarget : Conditional
{
    public SharedGameObject target;
    
    // Set abort type in inspector to Self
    // This will re-evaluate the branch when target changes
    
    public override TaskStatus OnUpdate()
    {
        return target.Value != null 
            ? TaskStatus.Success 
            : TaskStatus.Failure;
    }
}

Lower Priority Abort

csharp
// Use AbortType.LowerPriority to interrupt lower priority branches
[TaskCategory("Combat")]
public class IsUnderAttack : Conditional
{
    public SharedBool underAttack;
    
    // Set abort type to LowerPriority
    // Will interrupt patrol/idle when attacked
    
    public override TaskStatus OnUpdate()
    {
        return underAttack.Value 
            ? TaskStatus.Success 
            : TaskStatus.Failure;
    }
}

Integration with GAS

Ability Task Integration

csharp
[TaskCategory("Abilities")]
public class ActivateAbilitiesByTag : Action
{
    public SharedGameObject owner;
    public SharedString abilityTag;
    public SharedBool waitForCompletion = true;
    
    private AbilitySystemComponent _asc;
    private bool _activated;
    
    public override void OnStart()
    {
        _activated = false;
        
        if (owner.Value != null)
        {
            _asc = owner.Value.GetComponent<AbilitySystemComponent>();
        }
    }
    
    public override TaskStatus OnUpdate()
    {
        if (_asc == null)
            return TaskStatus.Failure;
        
        if (!_activated)
        {
            var spec = _asc.TryActivateAbilitiesByTag(
                GameplayTag.FromString(abilityTag.Value)
            );
            
            if (spec == null)
                return TaskStatus.Failure;
            
            _activated = true;
            
            if (!waitForCompletion.Value)
                return TaskStatus.Success;
        }
        
        // Wait for ability to complete
        if (_asc.HasActiveAbilityWithTag(GameplayTag.FromString(abilityTag.Value)))
        {
            return TaskStatus.Running;
        }
        
        return TaskStatus.Success;
    }
}

Debugging

Behavior Tree Debugging

csharp
public class BehaviorTreeDebugger : MonoBehaviour
{
    [SerializeField] private BehaviorTree _behaviorTree;
    [SerializeField] private bool _logTaskChanges = true;
    
    private void OnEnable()
    {
        if (_behaviorTree != null)
        {
            _behaviorTree.OnBehaviorStart += OnBehaviorStart;
            _behaviorTree.OnBehaviorRestart += OnBehaviorRestart;
            _behaviorTree.OnBehaviorEnd += OnBehaviorEnd;
        }
    }
    
    private void OnDisable()
    {
        if (_behaviorTree != null)
        {
            _behaviorTree.OnBehaviorStart -= OnBehaviorStart;
            _behaviorTree.OnBehaviorRestart -= OnBehaviorRestart;
            _behaviorTree.OnBehaviorEnd -= OnBehaviorEnd;
        }
    }
    
    private void OnBehaviorStart(Behavior behavior)
    {
        if (_logTaskChanges)
        {
            Debug.Log($"[BT] {name} Started");
        }
    }
    
    private void OnBehaviorRestart(Behavior behavior)
    {
        if (_logTaskChanges)
        {
            Debug.Log($"[BT] {name} Restarted");
        }
    }
    
    private void OnBehaviorEnd(Behavior behavior)
    {
        if (_logTaskChanges)
        {
            Debug.Log($"[BT] {name} Ended");
        }
    }
}

Best Practices

  1. Use shared variables - For data passing between tasks
  2. Keep tasks simple - Single responsibility
  3. Use conditional aborts - For responsive AI
  4. Cache component references - In OnStart
  5. Handle null gracefully - Return Failure on null
  6. Use task categories - Organize custom tasks
  7. Profile behavior trees - Can be expensive
  8. Use external trees - For reusable behaviors
  9. Document task descriptions - Use TaskDescription attribute
  10. Test edge cases - Target dies, interrupted, etc.

Troubleshooting

IssueSolution
Task never completesCheck for infinite Running state
Variables not syncedVerify shared variable binding
Abort not workingCheck abort type setting
Performance issuesReduce tree complexity, cache refs
Null referenceAdd null checks in OnUpdate
Task not foundCheck TaskCategory attribute

常见问题

Tools Unity Behavior Designer AI 技能有什么作用?

Behavior Designer patterns for AI behavior trees including task creation, shared variables, conditionals, and debugging.

为什么在 TypingMind 中使用 Tools Unity Behavior Designer?

因为您只需安装一次,就能搭配任何模型使用。Tools Unity Behavior Designer 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Tools Unity Behavior Designer?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/IdoCohen560/claude-unity-game-studio/tree/main/examples/my-first-game/.claude/skills/tools-unity-behavior-designer。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Tools Unity Behavior Designer?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Tools Unity Behavior Designer 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Tools Unity Behavior Designer 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Tools Unity Behavior Designer AI 技能免费吗?

是的。IdoCohen560 已在 GitHub 上根据 MIT 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇