Back to Other builds

Unity Asset · Documentation

Skill Tree Kit

Unity 6C#uGUI TextMeshProDOTweenv1.0.0
On this page

    Documentation

    Skill Tree Kit has four parts: the data (a SkillTreeAsset), the rules (SkillTreeManager), the UI (SkillTreeView, popups and side panels) and the editor tools to build and test it inside Unity.

    It does not decide what a skill does in your game. Nodes produce stats, flags and events; your code, or the binding components that ship with the kit, turn those into gameplay. I built it for my own incremental game, where the workshop tree has 198 nodes and its stats drive damage, stamina and spawn rates through binding components. The two example scenes are smaller versions of that setup.

    Highlights

    Visual tree editor

    Create, move, connect and duplicate nodes on a canvas, with snapping, auto-connect and validation.

    Live preview

    Buy nodes, reset and set the balance in a separate preview scene. Your open scene is not touched.

    Costs, levels and currencies

    Formula or fixed costs, multi-level nodes, several currencies per node and discounts from stats.

    Stats, flags and effects

    Stat modifiers, unlock flags and abilities, plus your own effects by inheriting one class.

    No-code integration

    Binding components push stats and flags into your scripts through UnityEvents.

    Stylable UI

    Ten node shapes, a color set per state, your own sprites, and dashed, textured or curved lines.

    Animation, audio and VFX

    DOTween animations, a sound per event with a pitch combo, and VFX drawn as UI meshes.

    Saves and respecs

    PlayerPrefs, a JSON file or your own storage. A refund gives back what was paid in each currency.

    Requirements And Dependencies

    • Unity 6: tested on 6000.0, 6000.3 and 6000.6, with Built-in, URP and HDRP.
    • Unity UI (uGUI): the tree, popups and panels are Canvas based.
    • TextMeshPro: every text in the runtime UI.
    • DOTween (free version is enough): all animations are DOTween tweens. It is a required dependency and is not bundled with the package; import it from the Asset Store first.
    • Input System: only used by the example scripts (for example the Tab key that opens the tree). The kit itself works with either input backend.

    Note

    If you do not want any animation, turn off Stock Animations in the view's Appearance settings, or enable Reduced Motion. DOTween still has to be in the project for the code to compile.

    Quick Start

    1. Open The Home Window

    After importing, the Skill Tree Kit Home window opens by itself (you can turn that off with Show at startup). You can always reopen it from Tools → Skill Tree → Home. From there you reach the tree editor, the preview, the popup editor and the example scenes.

    2. Open A Demo Scene

    • Examples/ExampleScenes/Popup/PopupExample.unity: a radial tree with a hover popup, a money counter and debug tools.
    • Examples/ExampleScenes/SidePanel/SidePanelExample.unity: a flat tree with a fixed detail panel and a HUD that reacts to stats and abilities.

    Press Play, click nodes to buy them and watch how the HUD changes. Both scenes use a debug currency, so you can add money from the debug panel.

    3. Create A Tree

    1. Right click in the Project window: Create → Skill Tree → Skill Tree.
    2. Double click the asset. The Skill Tree editor opens with a root node already placed.
    3. In Branches & stats, add your branches (id, name, color, base cost) and the stats your game understands (dmg, spd, gold…).
    4. Right click on the canvas to create nodes, then drag from the ● handle of one node to another to connect them.
    5. Select a node and fill the Node tab: name, icon, branch, cost, levels and effects.

    4. Put The Tree In A Scene

    1. Create an empty GameObject and add SkillTreeManager. Assign your tree asset.
    2. Create a Canvas and add a child with SkillTreeView. Assign the manager.
    3. Optionally add SkillNodePopup (hover tooltip) or SkillDetailPanel (fixed side panel) and point them to the view.

    The view builds the nodes, links and board at runtime; you do not need to place one GameObject per node.

    5. Connect Your Currency

    The manager spends through ISkillCurrency. Implement it on your wallet and drag that component into the manager's Currency Source field.

    using System;
    using SkillTreeKit;
    using UnityEngine;
    
    public class WalletCurrency : MonoBehaviour, ISkillCurrency
    {
        [SerializeField] long balance = 500;
    
        public long Balance => balance;
        public event Action BalanceChanged;
    
        public bool CanAfford(long amount) => balance >= amount;
    
        public bool TrySpend(long amount)
        {
            if (!CanAfford(amount)) return false;
            balance -= amount;
            BalanceChanged?.Invoke();
            return true;
        }
    
        public void Refund(long amount)
        {
            balance += amount;
            BalanceChanged?.Invoke();
        }
    }

    6. React To Purchases

    Stats are summed across every owned node and level, so a value of 35 in dmg means +35% damage if that is how your game reads it:

    SkillTreeManager tree = SkillTreeManager.Main;
    
    float damageBonus = tree.GetStat("dmg");
    bool canDash = tree.HasFlag("dash");
    
    tree.StatsChanged += () => player.Damage = baseDamage * (1f + tree.GetStat("dmg") / 100f);

    Or skip code entirely: add a SkillStatBinding, choose the stat and mode, and call your setter from its UnityEvent. See Connecting To Your Game.

    Folder Structure

    Everything lives under Assets/SkillTree. The Home window shows the same map and pings each folder when clicked.

    SkillTree/ ├── Runtime/ kit code, included in builds ├── Editor/ editor windows and tools └── Examples/ optional, can be deleted ├── ExampleScenes/ example scenes and their trees ├── Scripts/ example scripts ├── Editor/ example generators ├── Audio/ sounds ├── Vfx/ floating text, spark particles ├── Lines/ custom line sprites and renderer ├── Animators/ node animator example └── Fonts/ LuckiestGuy + license

    The runtime is split into Core (manager, currency, language), Data (assets and settings), Effects, Integration (binding components) and UI (view, popup, panels, graphics). Assemblies: SkillTreeKit.Runtime, SkillTreeKit.Editor, SkillTreeKit.Examples.

    Editor Windows

    Home

    Welcome window with quick actions (Tree Editor, New tree, Preview, Popup), the example scenes with an Open button and the folder map. Fixed size, opens centered over the editor.

    Tree Editor

    The main window. The left side is the canvas, the right side is the inspector with these tabs:

    TabWhat it edits
    NodeSelected node: name, description, icon, type, branch, cost, levels, currencies, effects, sound and VFX overrides. Also shows where the node is used in the scene.
    Branches & statsBranch ids, names, colors and base costs; stat ids, names and display formats.
    TreeTree id, cost settings (growth, milestone multiplier, level growth, discount stat), layout and the stat/flag bindings found in the scene.
    AppearanceThe SkillTreeView style of the scene that uses this tree, with a live interactive preview on the canvas.
    AudioSound per event with ▶ preview buttons.
    VFXEffect per event, played on the selected node.
    ValidateProblems such as unreachable nodes, missing roots or unknown branch ids.

    Canvas shortcuts

    ActionInput
    Create nodeRight click on empty canvas
    Connect nodesDrag from the ● handle, or Ctrl + drag
    Delete selectionDelete
    DuplicateCtrl + D
    Frame allF
    Pan / zoomMiddle mouse drag / scroll wheel

    The toolbar adds Snap, Names, Recalculate depth, Auto-connect with its distance, and shortcuts to Preview and Popup. The EN/ES selector on the right switches every kit window between English and Spanish.

    Preview

    Clones the canvas of the scene that uses the tree into a separate preview scene with its own manager and currency. Click buys, drag pans, wheel zooms. The toolbar has Buy all, Reset, Money ∞, a balance field, a cost multiplier, Frame and Rebuild. It pauses in Play mode.

    Popup Editor

    Edits a SkillPopupStyle on the left while showing the real popup on the right. A row of states (Available, No money, Locked, Requirement, Owned, Level 1/3, Max level) lets you check every text without playing. Create template turns the current design into a prefab.

    Core Concepts

    SkillTreeAsset

    A ScriptableObject that holds the whole design: branches, stats, nodes, node types, edges, cost and layout settings, audio, VFX and custom states. It contains no runtime state, so the same asset can be shared by several managers.

    SkillNodeData

    One node inside the asset. Key fields:

    • id, displayName, description, icon
    • typeId and branchId
    • costMode (Formula / Fixed), depth, costMultiplier, fixedCost
    • maxLevel, neighborUnlockLevel, levelCostGrowth
    • currencyId and extraCosts
    • prerequisiteMode, hiddenUntilFlag, effects

    SkillNodeType

    Defines how a group of nodes looks and behaves. Its role sets the rules (Normal needs one neighbor, Milestone needs all of them and costs more, Root is the start) and its shape sets the drawing: Square, Diamond, Octagon, Circle, Triangle, Pentagon, Hexagon, Shield, Star or a custom Polygon. Each type can also have its own size, corner radius, sprites and cost multiplier.

    SkillDefinition

    Optional reusable skill (Create → Skill Tree → Skill) with name, description, icon and effects. Assign it to several nodes or trees; read it through node.Name, node.Description, node.Icon and node.Effects, which fall back to the node's own fields.

    SkillTreeManager

    Runs the tree in play mode. It owns levels, spending, stats, flags, validators and saving, and raises events when something changes.

    SkillTreeManager tree = SkillTreeManager.Find("workshop");
    
    SkillPurchaseCheck check = tree.Check("power_1");
    if (check.Ok) tree.Purchase("power_1");
    
    int level = tree.GetLevel("power_1");
    bool owned = tree.IsOwned("power_1");
    long spent = tree.Spent;

    SkillTreeView

    Draws the tree inside a Canvas: board, links, nodes, badges and VFX layer. All of its look lives in Style (a SkillTreeViewStyle), editable from the Appearance tab.

    Popup And Detail Panel

    SkillNodePopup follows the hovered node and is driven by a SkillPopupStyle plus an optional prefab template. SkillDetailPanel is a fixed panel built from your own TextMeshPro texts, image and buttons; it can follow hover or show only the selected node.

    Setting Up Skills

    Identity

    Node ids are the contract with your code and your save files. Keep them short and stable:

    root
    power_1
    power_2
    economy_milestone

    Renaming a node's display name is safe; changing its id breaks saves that already own it.

    Costs

    With Formula cost, the price is calculated from the branch and the node's depth:

    cost = branch.baseCost × node.costMultiplier × growth ^ depth
           × milestoneMultiplier (milestones only)
           rounded to steps of 5 / 10 / 50

    Default values are growth = 1.65 and milestoneMultiplier = 1.5, both in the Tree tab. Use Fixed for a hand-picked price. Recalculate depth sets depth to the number of hops from the root.

    Multi-Level Skills

    • maxLevel: how many times the node can be bought.
    • levelCostGrowth: price growth per level (0 uses the tree's levelGrowth, 1.5).
    • levelCosts: optional fixed price per level, overrides growth.
    • neighborUnlockLevel: level needed before neighbors open.

    Multi-Currency Costs

    Each node pays in its currencyId (empty = main currency) plus any extraCosts. Register the extra currencies in the manager's Currencies list or from code:

    tree.RegisterCurrency("gems", gemWallet);
    
    List<SkillCostEntry> costs = new List<SkillCostEntry>();
    tree.GetCosts("forge_3", costs);
    foreach (SkillCostEntry c in costs)
        Debug.Log($"{c.amount} {(string.IsNullOrEmpty(c.currencyId) ? "coins" : c.currencyId)}");

    Prerequisites

    prerequisiteMode decides which owned neighbors a node needs:

    ModeRule
    AutoRoot needs nothing, milestones need all neighbors, the rest need any one.
    NoneAlways available.
    AnyAt least one owned neighbor.
    AllEvery neighbor owned.

    Hidden Nodes And Branches

    Set hiddenUntilFlag on a node or a whole branch. It stays invisible until your game raises that flag:

    SkillTreeManager.Main.SetFlag("secret_branch", true);

    Connecting Nodes

    Manual Edges

    Drag from the ● handle (or Ctrl + drag) between two nodes. Select an edge to change its bend or delete it.

    Automatic Edges

    Turn on Auto-connect and set a distance. Nodes closer than that distance are linked every time you move or add one. Manual edges are kept, and removing an automatic edge remembers it, so it is not created again.

    Runtime Edges

    Add or remove edges while playing. ResetEdges goes back to the asset's edges.

    tree.AddEdge("power_3", "secret_1");
    tree.RemoveEdge("eco_2", "eco_3");
    tree.ResetEdges();
    
    tree.GraphChanged += () => Debug.Log("Tree graph changed");

    Effects And Stats

    Each node has a list of effects, added with Add effect… in the Node tab.

    EffectFieldsRead with
    StatModifierEffectstatId, value (× level) or perLevelGetStat(id)
    UnlockFlagEffectflagId, atLevelHasFlag(id)
    ActiveAbilityEffectabilityId, cooldown, durationHasFlag(id)

    Custom Effects

    Inherit from SkillEffect. Mark it [Serializable] and it appears in Add effect… automatically. Implement ISkillStatContributor if it should add to stats.

    using System;
    using SkillTreeKit;
    using UnityEngine;
    
    [Serializable]
    public class SpawnPetEffect : SkillEffect
    {
        public GameObject petPrefab;
    
        public override string Describe(SkillTreeAsset tree) => "Summons a pet";
    
        public override void OnAcquired(SkillEffectContext context)
        {
            if (context.FromLoad || context.Level > 1) return;
            UnityEngine.Object.Instantiate(petPrefab);
        }
    
        public override void OnRevoked(SkillEffectContext context)
        {
            PetManager.Instance.Dismiss();
        }
    }

    Discounts

    Set cost.discountStatId in the Tree tab (for example "ctn"). Every point of that stat lowers future prices through EffectiveCostMultiplier.

    Connecting To Your Game

    The binding components in Runtime/Integration find the manager, listen to it and call your code through UnityEvents. The examples keep them in a Connections child under the manager, with one GameObject per stat or flag.

    SkillStatBinding

    Reads a stat, converts it with a mode and a base value, and sends the result to onValue.

    ModeResultExample (base 10, stat 25)
    Rawstat25
    Addbase + stat35
    Percentbase × (1 + stat / 100)12.5
    PercentReductionbase × (1 − stat / 100)7.5
    Fractionbase × stat / 1002.5

    SkillFlagBinding

    Shows or hides GameObjects and fires onUnlocked / onLocked when a flag changes. The SidePanel example uses it to show the ability rows (act3 to act5) once they are bought.

    SkillNodeListener

    Watches one node: onLevel(int), onAcquired, onMaxed and onLost.

    In The Game Panel

    The Node and Tree tabs list, for each stat, flag and node, every method in the scene that receives it. Click an entry to select it, or press + to create the missing binding. Stats with nothing connected show No connection.

    For logic that does not fit a UnityEvent, inherit from SkillTreeLink. Apply() runs on enable and after every change of the tree.

    using SkillTreeKit;
    using UnityEngine;
    
    public class ConveyorSpeedLink : SkillTreeLink
    {
        [SerializeField] Conveyor[] conveyors;
    
        protected override void Apply()
        {
            float speed = 1f + Manager.GetStat("spd") / 100f;
            foreach (Conveyor c in conveyors) c.SpeedMultiplier = speed;
        }
    }

    Purchase Rules And Validators

    Check(id) returns everything the UI needs before buying: result, current and next level, reason and costs.

    ResultMeaning
    SuccessCan be bought now.
    LockedPrerequisites not met.
    NotEnoughCurrencyMissing money in one of the currencies.
    AlreadyOwnedAlready at max level.
    HiddenHidden by a flag.
    BlockedA validator refused it; see Reason.
    UnknownNodeThe id does not exist in the tree.

    Add your own rules with ISkillPurchaseValidator, either in the manager's Validators list or with AddValidator:

    using SkillTreeKit;
    using UnityEngine;
    
    public class ChapterGate : MonoBehaviour, ISkillPurchaseValidator
    {
        [SerializeField] int requiredChapter = 2;
    
        public bool CanPurchase(SkillTreeManager manager, SkillNodeData node, int nextLevel, out string reason)
        {
            reason = $"Reach chapter {requiredChapter}";
            return node.branchId != "endgame" || GameProgress.Chapter >= requiredChapter;
        }
    }

    For simple cases, SkillRequirementValidator does it without code: per node, a required flag, a starting level and the message to show.

    Saving And Loading

    Pick a Save Mode on the manager: None, PlayerPrefs, JsonFile or Custom. With Load On Awake and Auto Save on (the default) you do not need any code. Levels and the amount paid in each currency are stored, so refunds stay exact. ToJson lets you embed the tree in your own save file.

    tree.Save();
    tree.Load();
    tree.DeleteSave();
    
    string json = tree.ToJson();
    tree.LoadFromJson(json);

    Custom Storage

    using SkillTreeKit;
    using UnityEngine;
    
    public class CloudSkillStorage : MonoBehaviour, ISkillTreeStorage
    {
        public string Read(string key) => CloudSave.Get(key);
        public void Write(string key, string json) => CloudSave.Set(key, json);
        public void Delete(string key) => CloudSave.Remove(key);
    }

    Assign it to the manager's Storage field with mode Custom, or call tree.SetStorage(storage, load: true).

    Refunds And Respecs

    Enable Allow Refunds and choose a Refund Ratio (1 = full price back). In the tree, right clicking an owned node refunds one level. ResetTree(true) is a full respec.

    if (tree.CanRefund("power_2") == SkillRefundResult.Success)
        tree.TryRefund("power_2");
    
    tree.ResetTree(refund: true);
    • Required: another owned node depends on this one, refund it first.
    • Disabled: refunds are off in the manager.
    • NotOwned: nothing to refund.

    Events

    Manager Events

    tree.NodePurchased  += node => Analytics.Log("skill", node.id);
    tree.LevelChanged   += (node, level) => { };
    tree.NodeRefunded   += (node, level) => { };
    tree.PurchaseFailed += (node, result) => { };
    tree.StatsChanged   += RefreshPlayer;
    tree.FlagAdded      += flag => { };
    tree.TreeReset      += () => { };
    tree.Loaded         += () => { };

    The same moments are also exposed as UnityEvents on the manager (onNodeLeveled, onNodeRefunded, onPurchaseFailed, onTreeReset, onTreeChanged).

    View Events

    SkillTreeView reports what the player sees: NodeHovered, NodeClicked, SelectionChanged, NodeRevealed, NodeStateChanged, NodeLeveled, NodeFailed and NodeCustomStateChanged. Add SkillViewEvents to wire them in the inspector, with an optional node id filter.

    Customizing The UI

    Everything below is in the view's Style and in the Appearance tab, where changes show up in the live preview immediately.

    Colors By State

    By default nodes use their branch color. Turn on customStateColors to set fill, border and icon colors for Available, No money, Owned and Locked, and customLineColors for links.

    Shapes And Sprites

    Node shapes come from node types. For your own art, set backgroundSprite, boardSprite and per-type border and fill sprites; they are tinted by state. Turn off drawBackground and showFrame to draw over your own canvas.

    Lines

    • linkRouting: Curve or Orthogonal.
    • dashedLines, showArrows, showLineFlow.
    • arrowSprite and lineSprite (repeated texture with scroll speed).
    • linkRenderer: a SkillLinkRenderer asset that builds the line mesh itself.
    using SkillTreeKit.UI;
    using UnityEngine;
    
    [CreateAssetMenu(menuName = "Skill Tree/Bead Line")]
    public class BeadLinkRenderer : SkillLinkRenderer
    {
        public override void Draw(SkillLinkDrawContext context)
        {
            SkillLinkMesh.Strip(context.Mesh, context.Points, context.Width, context.Color);
            foreach (Vector2 point in context.Points)
                SkillLinkMesh.Circle(context.Mesh, point, context.Width * 1.5f, context.Color);
        }
    }

    Click Behaviour And Selection

    clickAction is Purchase, Select or SelectThenPurchase. Use view.Select(id), view.PurchaseSelected() and view.ClearSelection() for gamepad or custom buttons. showAllNodes reveals locked nodes with a padlock badge.

    Popup

    Create a style (Create → Skill Tree → Popup Style): placement (Auto, Below, Above, Right, Left), sizes, sections, fonts, colors, sprites, texts and animation. Create template in the Popup editor turns the design into a prefab you can rearrange; the style keeps applying to it. Turn off Use style on the template to control its look only from the prefab.

    Custom States

    tree.customStates adds your own states on top of the built-in ones, each with colors, a badge and a pulse. Rules: Manual, ReadyToBuy, NotEnoughCurrency, PartiallyLeveled, Maxed, NewlyAvailable and Flag. Manual states are set from code:

    view.SetNodeState("forge_1", "event_sale");
    view.ClearNodeState("forge_1");

    Animations

    style.animation groups reveal, purchase, shake, hover, idle pulse and link timings, each with duration and ease. Tweens run on the kit's own clock, so they also play inside the editor previews.

    Custom Node Animator

    Replace the stock animations with a SkillNodeAnimator asset assigned to style.nodeAnimator. Override only the moments you care about:

    using DG.Tweening;
    using SkillTreeKit.UI;
    using UnityEngine;
    
    [CreateAssetMenu(menuName = "Skill Tree/Spin Animator")]
    public class SpinAnimator : SkillNodeAnimator
    {
        public override Tween Purchase(SkillNodeAnimContext c)
        {
            SkillMotionLayer layer = c.Motion.Action;
            Tween t = Value(0f, 1f, 0.5f, Ease.OutBack, p => layer.rotation = 360f * p);
            t.OnKill(layer.Reset);
            return t;
        }
    }

    A full example ships in Examples/Scripts/BouncyNodeAnimator.cs.

    Audio

    Sounds are stored in the tree (tree.audio): purchase, level up, max level, milestone, not enough currency, locked, refund, reset, hover and select, each with volume and pitch variation. Buying in quick succession raises the pitch as a combo. A node can override its purchase sound.

    Add SkillTreeAudio to the manager's GameObject to play them: mixer group, master volume, mute, minimum interval and number of voices.

    VFX

    tree.vfx assigns an effect to each event: Purchase, LevelUp, MaxLevel, Milestone, Unlocked, Fail and Refund. Built-in shapes (Burst, Ring, Sparkle, Confetti, Glow) are drawn as UI meshes, so they work in Screen Space Overlay without cameras. Prefabs with ParticleSystems are converted to UI particles automatically.

    using SkillTreeKit;
    using UnityEngine;
    
    [CreateAssetMenu(menuName = "Skill Tree/Shake Camera Vfx")]
    public class ShakeCameraVfx : SkillVfxEffect
    {
        public override void Play(SkillVfxContext context)
        {
            if (context.Event == SkillVfxEvent.Milestone) CameraShake.Play(0.3f);
        }
    }

    Language

    The kit is in English with Spanish included. Editor windows switch with the EN/ES selector. At runtime, texts generated by the kit (effect descriptions, debug panel) follow SkillText.Language:

    SkillText.Language = SkillLanguage.Spanish;
    SkillText.Changed += RefreshMyTexts;

    Public API Reference

    Finding A Tree

    Main is the first manager in the scene; Find looks one up by SkillTreeAsset.treeId.

    SkillTreeManager.Main
    SkillTreeManager.Find("tree_id")

    Queries

    int  GetLevel(string id)
    int  GetMaxLevel(string id)
    bool IsOwned(string id)
    bool IsMaxed(string id)
    bool IsAvailable(string id)
    bool IsVisible(string id)
    SkillNodeState GetState(string id)
    IReadOnlyList<string> GetNeighbors(string id)
    IEnumerable<string> OwnedIds

    Buying And Levels

    Unlock grants a node for free.

    SkillPurchaseCheck  Check(string id)
    SkillPurchaseCheck  Purchase(string id)
    SkillPurchaseResult TryPurchase(string id)
    void Unlock(string id)
    void SetLevel(string id, int level)
    int  PurchaseAllAvailable(bool free)

    Costs And Currencies

    long GetCost(string id)
    long GetLevelCost(string id, int level)
    void GetCosts(string id, List<SkillCostEntry> into)
    long GetTotalTreeCost()
    long GetRemainingCost()
    long Spent
    void RegisterCurrency(string currencyId, ISkillCurrency source)

    Stats And Flags

    float GetStat(string statId, float defaultValue = 0f)
    float GetStatMax(string statId)
    bool  HasFlag(string flagId)
    void  SetFlag(string flagId, bool value)
    void  Refresh()

    Recommended Integration Pattern

    1. One SkillTreeAsset per progression screen; the asset is design, not save data.
    2. Name stats by meaning (dmg, spd) and let the tree sum them.
    3. Read stats through bindings or StatsChanged, not every frame.
    4. Implement ISkillCurrency on your existing wallet instead of copying balances.
    5. Put game-specific rules in validators, not in the tree asset.
    6. Test prices with the Preview window (Buy all, cost multiplier) before balancing in Play mode.

    What Is Included

    Example Scenes

    • PopupExample: 15-node radial tree, popup template, money box, debug panel.
    • SidePanelExample: 33-node flat tree, detail panel prefab, stat HUD, ability flags, level-up VFX.

    Example Scripts

    • SkillTreeExampleToggle: Tab opens and closes the tree, Esc closes.
    • SkillHudRow, SkillBalanceText: HUD texts that flash on change.
    • BouncyNodeAnimator, WavyLinkRenderer, FloatingTextVfx, SkillParticleTint.

    Editor Tools

    • Home, Tree Editor, Preview and Popup windows.
    • Example generators under Tools → Skill Tree → Examples.
    • SkillTreeDebug: in-game panel with totals, progress bar, reset and buy all.

    Troubleshooting

    The Kit Does Not Compile

    DOTween is missing. Import it from the Asset Store and run its setup once.

    The Tree Is Empty In Play Mode

    • The view has no manager assigned, or the manager has no tree.
    • The tree has no root node. Check the Validate tab.

    A Node Cannot Be Bought

    • Log tree.Check(id): the result and Reason tell you which rule failed.
    • Milestones need every neighbor; switch prerequisiteMode if that is not intended.
    • An extra currency has no source registered.

    Progress Is Not Saved

    Check Save Mode and Auto Save. Two managers with the same Save Key overwrite each other; give each one its own key.

    A Stat Changes Nothing In The Game

    Open the node in the editor: if In the game says No connection, press + to create a SkillStatBinding and pick your setter.

    Icons Look Invisible

    The icon shader uses the image luminance as a mask. Use dark icons with alpha; pure white icons are tinted away.

    Particles Do Not Show In The Canvas

    Keep vfx.particlesInUI on. Prefabs with ParticleSystems are drawn as UI only when that option is enabled.

    Support And Feedback

    Found a bug or missing something? Write to me with your Unity version, a short description and, if you can, a screenshot of the Validate tab.

    © 2026 Eduardo Castro Skill Tree Kit v1.0.0
    Volver a Otros proyectos

    Asset de Unity · Documentación

    Skill Tree Kit

    Unity 6C#uGUI TextMeshProDOTweenv1.0.0
    En esta página

      Documentación

      Skill Tree Kit tiene cuatro partes: los datos (un SkillTreeAsset), las reglas (SkillTreeManager), la interfaz (SkillTreeView, popups y paneles laterales) y las herramientas de editor para construirlo y probarlo dentro de Unity.

      No decide lo que una habilidad hace en tu juego. Los nodos producen stats, flags y eventos; tu código, o los componentes de conexión que trae el kit, los convierten en jugabilidad. Lo hice para mi propio juego incremental: ahí el árbol del taller tiene 198 nodos y sus stats mueven el daño, la estamina y la aparición de objetos mediante los componentes de conexión. Las dos escenas de ejemplo son versiones pequeñas de ese montaje.

      Características

      Editor visual del árbol

      Crea, mueve, conecta y duplica nodos en un lienzo, con ajuste a la cuadrícula, conexión automática y validación.

      Preview en vivo

      Compra nodos, reinicia y cambia el saldo en una escena de preview aparte. Tu escena abierta no se toca.

      Costos, niveles y monedas

      Costos por fórmula o fijos, nodos de varios niveles, varias monedas por nodo y descuentos por stats.

      Stats, flags y efectos

      Modificadores de stats, flags de desbloqueo y habilidades, más tus propios efectos heredando una clase.

      Integración sin código

      Componentes de conexión que envían stats y flags a tus scripts mediante UnityEvents.

      Interfaz personalizable

      Diez formas de nodo, colores para cada estado, tus propios sprites y líneas discontinuas, con textura o curvas.

      Animación, audio y VFX

      Animaciones con DOTween, un sonido por evento con combo de tono y VFX dibujados como mallas de UI.

      Guardado y reembolsos

      PlayerPrefs, un archivo JSON o tu propio almacenamiento. Un reembolso devuelve lo pagado en cada moneda.

      Requisitos y dependencias

      • Unity 6: probado en 6000.0, 6000.3 y 6000.6, con Built-in, URP y HDRP.
      • Unity UI (uGUI): el árbol, los popups y los paneles usan Canvas.
      • TextMeshPro: todos los textos de la interfaz.
      • DOTween (la versión gratuita basta): todas las animaciones son tweens de DOTween. Es una dependencia obligatoria y no viene dentro del paquete; impórtalo antes desde la Asset Store.
      • Input System: solo lo usan los scripts de ejemplo (por ejemplo, la tecla Tab que abre el árbol). El kit funciona con cualquiera de los dos sistemas de input.

      Nota

      Si no quieres ninguna animación, desactiva Stock Animations en la Apariencia de la vista o activa Reduced Motion. DOTween tiene que seguir en el proyecto para que el código compile.

      Inicio rápido

      1. Abre la ventana Home

      Al importar, la ventana Home de Skill Tree Kit se abre sola (puedes desactivarlo con Show at startup). Siempre puedes volver a abrirla desde Tools → Skill Tree → Home. Desde ahí llegas al editor del árbol, la preview, el editor de popup y las escenas de ejemplo.

      2. Abre una escena de ejemplo

      • Examples/ExampleScenes/Popup/PopupExample.unity: un árbol radial con popup al pasar el ratón, contador de dinero y herramientas de debug.
      • Examples/ExampleScenes/SidePanel/SidePanelExample.unity: un árbol plano con panel de detalle fijo y un HUD que reacciona a stats y habilidades.

      Dale a Play, haz clic en los nodos para comprarlos y mira cómo cambia el HUD. Las dos escenas usan una moneda de debug, así que puedes añadir dinero desde el panel de debug.

      3. Crea un árbol

      1. Clic derecho en la ventana Project: Create → Skill Tree → Skill Tree.
      2. Doble clic en el asset. Se abre el editor Skill Tree con un nodo raíz ya colocado.
      3. En Ramas y stats, añade tus ramas (id, nombre, color, costo base) y los stats que entiende tu juego (dmg, spd, gold…).
      4. Clic derecho en el lienzo para crear nodos y arrastra desde el ● de un nodo hasta otro para conectarlos.
      5. Selecciona un nodo y rellena la pestaña Nodo: nombre, icono, rama, costo, niveles y efectos.

      4. Pon el árbol en una escena

      1. Crea un GameObject vacío y añade SkillTreeManager. Asigna tu árbol.
      2. Crea un Canvas y añade un hijo con SkillTreeView. Asigna el manager.
      3. Si quieres, añade SkillNodePopup (popup al pasar el ratón) o SkillDetailPanel (panel lateral fijo) y apúntalos a la vista.

      La vista construye los nodos, las líneas y el tablero en tiempo de ejecución; no tienes que colocar un GameObject por nodo.

      5. Conecta tu moneda

      El manager gasta a través de ISkillCurrency. Impleméntalo en tu monedero y arrastra ese componente al campo Currency Source del manager.

      using System;
      using SkillTreeKit;
      using UnityEngine;
      
      public class WalletCurrency : MonoBehaviour, ISkillCurrency
      {
          [SerializeField] long balance = 500;
      
          public long Balance => balance;
          public event Action BalanceChanged;
      
          public bool CanAfford(long amount) => balance >= amount;
      
          public bool TrySpend(long amount)
          {
              if (!CanAfford(amount)) return false;
              balance -= amount;
              BalanceChanged?.Invoke();
              return true;
          }
      
          public void Refund(long amount)
          {
              balance += amount;
              BalanceChanged?.Invoke();
          }
      }

      6. Reacciona a las compras

      Los stats se suman entre todos los nodos y niveles comprados, así que un 35 en dmg significa +35% de daño si así lo interpreta tu juego:

      SkillTreeManager tree = SkillTreeManager.Main;
      
      float damageBonus = tree.GetStat("dmg");
      bool canDash = tree.HasFlag("dash");
      
      tree.StatsChanged += () => player.Damage = baseDamage * (1f + tree.GetStat("dmg") / 100f);

      O hazlo sin código: añade un SkillStatBinding, elige el stat y el modo, y llama a tu setter desde su UnityEvent. Mira Conectar con tu juego.

      Estructura de carpetas

      Todo vive en Assets/SkillTree. La ventana Home muestra el mismo mapa y resalta cada carpeta al hacer clic.

      SkillTree/ ├── Runtime/ código del kit, va en el build ├── Editor/ ventanas y herramientas del editor └── Examples/ opcional, se puede borrar ├── ExampleScenes/ escenas de ejemplo y sus árboles ├── Scripts/ scripts de ejemplo ├── Editor/ generadores de ejemplos ├── Audio/ sonidos ├── Vfx/ texto flotante, partículas ├── Lines/ sprites y renderer de líneas ├── Animators/ ejemplo de animador de nodos └── Fonts/ LuckiestGuy + licencia

      El runtime se divide en Core (manager, moneda, idioma), Data (assets y ajustes), Effects, Integration (componentes de conexión) y UI (vista, popup, paneles, gráficos). Ensamblados: SkillTreeKit.Runtime, SkillTreeKit.Editor, SkillTreeKit.Examples.

      Ventanas del editor

      Home

      Ventana de bienvenida con accesos rápidos (Tree Editor, New tree, Preview, Popup), las escenas de ejemplo con un botón Open y el mapa de carpetas. Tiene tamaño fijo y se abre centrada sobre el editor.

      Editor del árbol

      La ventana principal. A la izquierda está el lienzo y a la derecha el inspector con estas pestañas:

      PestañaQué edita
      NodoEl nodo seleccionado: nombre, descripción, icono, tipo, rama, costo, niveles, monedas, efectos, sonido y VFX propios. También muestra dónde se usa el nodo en la escena.
      Ramas y statsIds, nombres, colores y costos base de las ramas; ids, nombres y formatos de los stats.
      ÁrbolId del árbol, ajustes de costo (crecimiento, multiplicador de hito, crecimiento por nivel, stat de descuento), disposición y las conexiones de stats y flags encontradas en la escena.
      AparienciaEl estilo del SkillTreeView de la escena que usa este árbol, con una preview interactiva en el lienzo.
      AudioSonido por evento con botones ▶ para escucharlo.
      VFXEfecto por evento, reproducido sobre el nodo seleccionado.
      ValidarProblemas como nodos inalcanzables, falta de raíz o ids de rama desconocidos.

      Atajos del lienzo

      AcciónEntrada
      Crear nodoClic derecho en el lienzo vacío
      Conectar nodosArrastrar desde el ●, o Ctrl + arrastrar
      Borrar selecciónSupr
      DuplicarCtrl + D
      Encuadrar todoF
      Mover / zoomArrastrar con botón central / rueda del ratón

      La barra añade Snap, Names, Recalculate depth, Auto-connect con su distancia, y accesos a Preview y Popup. El selector EN/ES de la derecha cambia todas las ventanas del kit entre inglés y español.

      Preview

      Clona el canvas de la escena que usa el árbol en una escena de preview aparte, con su propio manager y su propia moneda. Clic compra, arrastrar mueve, la rueda hace zoom. La barra tiene Comprar todo, Reiniciar, Dinero ∞, el saldo, un multiplicador de costos, Encuadrar y Reconstruir. Se pausa en Play.

      Editor de popup

      Edita un SkillPopupStyle a la izquierda mientras muestra el popup real a la derecha. Una fila de estados (Disponible, Sin dinero, Bloqueado, Requisito, Comprado, Nivel 1/3, Nivel máximo) te deja revisar todos los textos sin darle a Play. Crear plantilla convierte el diseño actual en un prefab.

      Conceptos principales

      SkillTreeAsset

      Un ScriptableObject con todo el diseño: ramas, stats, nodos, tipos de nodo, conexiones, ajustes de costo y disposición, audio, VFX y estados propios. No guarda estado de partida, así que el mismo asset lo pueden compartir varios managers.

      SkillNodeData

      Un nodo dentro del asset. Campos principales:

      • id, displayName, description, icon
      • typeId y branchId
      • costMode (Formula / Fixed), depth, costMultiplier, fixedCost
      • maxLevel, neighborUnlockLevel, levelCostGrowth
      • currencyId y extraCosts
      • prerequisiteMode, hiddenUntilFlag, effects

      SkillNodeType

      Define cómo se ve y se comporta un grupo de nodos. Su rol marca las reglas (Normal pide un vecino, Hito pide todos y cuesta más, Raíz es el inicio) y su forma el dibujo: Cuadro, Rombo, Octágono, Círculo, Triángulo, Pentágono, Hexágono, Escudo, Estrella o un Polígono propio. Cada tipo puede tener además su tamaño, radio de esquinas, sprites y multiplicador de costo.

      SkillDefinition

      Habilidad reutilizable opcional (Create → Skill Tree → Skill) con nombre, descripción, icono y efectos. Asígnala a varios nodos o árboles; se lee con node.Name, node.Description, node.Icon y node.Effects, que usan los campos del propio nodo si no hay definición.

      SkillTreeManager

      Maneja el árbol durante el juego. Lleva los niveles, el gasto, los stats, los flags, los validadores y el guardado, y lanza eventos cuando algo cambia.

      SkillTreeManager tree = SkillTreeManager.Find("workshop");
      
      SkillPurchaseCheck check = tree.Check("power_1");
      if (check.Ok) tree.Purchase("power_1");
      
      int level = tree.GetLevel("power_1");
      bool owned = tree.IsOwned("power_1");
      long spent = tree.Spent;

      SkillTreeView

      Dibuja el árbol dentro de un Canvas: tablero, líneas, nodos, insignias y capa de VFX. Todo su aspecto vive en Style (un SkillTreeViewStyle), editable desde la pestaña Apariencia.

      Popup y panel de detalle

      SkillNodePopup sigue al nodo bajo el ratón y se controla con un SkillPopupStyle más una plantilla prefab opcional. SkillDetailPanel es un panel fijo armado con tus propios textos de TextMeshPro, imagen y botones; puede seguir al ratón o mostrar solo el nodo seleccionado.

      Configurar habilidades

      Identidad

      Los ids de los nodos son el contrato con tu código y tus partidas guardadas. Mantenlos cortos y estables:

      root
      power_1
      power_2
      economy_milestone

      Cambiar el nombre visible de un nodo es seguro; cambiar su id rompe las partidas que ya lo tienen.

      Costos

      Con costo Formula, el precio se calcula a partir de la rama y la profundidad del nodo:

      costo = rama.baseCost × nodo.costMultiplier × growth ^ profundidad
              × milestoneMultiplier (solo hitos)
              redondeado a pasos de 5 / 10 / 50

      Los valores por defecto son growth = 1.65 y milestoneMultiplier = 1.5, ambos en la pestaña Árbol. Usa Fixed para un precio elegido a mano. Recalculate depth pone como profundidad el número de saltos desde la raíz.

      Habilidades de varios niveles

      • maxLevel: cuántas veces se puede comprar el nodo.
      • levelCostGrowth: crecimiento del precio por nivel (0 usa el levelGrowth del árbol, 1.5).
      • levelCosts: precio fijo opcional por nivel, sustituye al crecimiento.
      • neighborUnlockLevel: nivel necesario para abrir a los vecinos.

      Costos en varias monedas

      Cada nodo paga en su currencyId (vacío = moneda principal) más sus extraCosts. Registra las monedas extra en la lista Currencies del manager o desde código:

      tree.RegisterCurrency("gems", gemWallet);
      
      List<SkillCostEntry> costs = new List<SkillCostEntry>();
      tree.GetCosts("forge_3", costs);
      foreach (SkillCostEntry c in costs)
          Debug.Log($"{c.amount} {(string.IsNullOrEmpty(c.currencyId) ? "coins" : c.currencyId)}");

      Requisitos

      prerequisiteMode decide qué vecinos comprados necesita un nodo:

      ModoRegla
      AutoLa raíz no necesita nada, los hitos necesitan todos sus vecinos y el resto uno cualquiera.
      NoneSiempre disponible.
      AnyAl menos un vecino comprado.
      AllTodos los vecinos comprados.

      Nodos y ramas ocultos

      Pon hiddenUntilFlag en un nodo o en una rama entera. Se queda invisible hasta que tu juego active ese flag:

      SkillTreeManager.Main.SetFlag("secret_branch", true);

      Conectar nodos

      Conexiones manuales

      Arrastra desde el ● (o Ctrl + arrastrar) entre dos nodos. Selecciona una conexión para cambiar su bend o borrarla.

      Conexiones automáticas

      Activa Auto-connect y elige una distancia. Los nodos más cercanos que esa distancia se conectan cada vez que mueves o añades uno. Las conexiones manuales se mantienen, y si quitas una automática se recuerda para no volver a crearla.

      Conexiones en tiempo de ejecución

      Añade o quita conexiones mientras se juega. ResetEdges vuelve a las conexiones del asset.

      tree.AddEdge("power_3", "secret_1");
      tree.RemoveEdge("eco_2", "eco_3");
      tree.ResetEdges();
      
      tree.GraphChanged += () => Debug.Log("Tree graph changed");

      Efectos y stats

      Cada nodo tiene una lista de efectos, que se añaden con Añadir efecto… en la pestaña Nodo.

      EfectoCamposSe lee con
      StatModifierEffectstatId, value (× nivel) o perLevelGetStat(id)
      UnlockFlagEffectflagId, atLevelHasFlag(id)
      ActiveAbilityEffectabilityId, cooldown, durationHasFlag(id)

      Efectos propios

      Hereda de SkillEffect. Márcalo con [Serializable] y aparecerá solo en Añadir efecto…. Implementa ISkillStatContributor si debe sumar a los stats.

      using System;
      using SkillTreeKit;
      using UnityEngine;
      
      [Serializable]
      public class SpawnPetEffect : SkillEffect
      {
          public GameObject petPrefab;
      
          public override string Describe(SkillTreeAsset tree) => "Summons a pet";
      
          public override void OnAcquired(SkillEffectContext context)
          {
              if (context.FromLoad || context.Level > 1) return;
              UnityEngine.Object.Instantiate(petPrefab);
          }
      
          public override void OnRevoked(SkillEffectContext context)
          {
              PetManager.Instance.Dismiss();
          }
      }

      Descuentos

      Pon cost.discountStatId en la pestaña Árbol (por ejemplo "ctn"). Cada punto de ese stat abarata los precios siguientes a través de EffectiveCostMultiplier.

      Conectar con tu juego

      Los componentes de Runtime/Integration encuentran el manager, lo escuchan y llaman a tu código mediante UnityEvents. Los ejemplos los guardan en un hijo Connections bajo el manager, con un GameObject por stat o flag.

      SkillStatBinding

      Lee un stat, lo convierte con un modo y un valor base, y envía el resultado a onValue.

      ModoResultadoEjemplo (base 10, stat 25)
      Rawstat25
      Addbase + stat35
      Percentbase × (1 + stat / 100)12.5
      PercentReductionbase × (1 − stat / 100)7.5
      Fractionbase × stat / 1002.5

      SkillFlagBinding

      Muestra u oculta GameObjects y lanza onUnlocked / onLocked cuando cambia un flag. El ejemplo SidePanel lo usa para mostrar las filas de habilidades (act3 a act5) cuando se compran.

      SkillNodeListener

      Vigila un nodo: onLevel(int), onAcquired, onMaxed y onLost.

      Panel «En el juego»

      Las pestañas Nodo y Árbol listan, para cada stat, flag y nodo, todos los métodos de la escena que lo reciben. Haz clic en uno para seleccionarlo, o pulsa + para crear la conexión que falta. Los stats sin nada conectado muestran Sin conexión.

      Para lógica que no cabe en un UnityEvent, hereda de SkillTreeLink. Apply() se ejecuta al activarse y después de cada cambio del árbol.

      using SkillTreeKit;
      using UnityEngine;
      
      public class ConveyorSpeedLink : SkillTreeLink
      {
          [SerializeField] Conveyor[] conveyors;
      
          protected override void Apply()
          {
              float speed = 1f + Manager.GetStat("spd") / 100f;
              foreach (Conveyor c in conveyors) c.SpeedMultiplier = speed;
          }
      }

      Reglas de compra y validadores

      Check(id) devuelve todo lo que la interfaz necesita antes de comprar: resultado, nivel actual y siguiente, motivo y costos.

      ResultadoSignificado
      SuccessSe puede comprar ahora.
      LockedNo cumple los requisitos.
      NotEnoughCurrencyFalta dinero en alguna de las monedas.
      AlreadyOwnedYa está en el nivel máximo.
      HiddenOculto por un flag.
      BlockedUn validador lo rechazó; mira Reason.
      UnknownNodeEl id no existe en el árbol.

      Añade tus propias reglas con ISkillPurchaseValidator, en la lista Validators del manager o con AddValidator:

      using SkillTreeKit;
      using UnityEngine;
      
      public class ChapterGate : MonoBehaviour, ISkillPurchaseValidator
      {
          [SerializeField] int requiredChapter = 2;
      
          public bool CanPurchase(SkillTreeManager manager, SkillNodeData node, int nextLevel, out string reason)
          {
              reason = $"Reach chapter {requiredChapter}";
              return node.branchId != "endgame" || GameProgress.Chapter >= requiredChapter;
          }
      }

      Para casos simples, SkillRequirementValidator lo hace sin código: por nodo, un flag requerido, el nivel desde el que aplica y el mensaje a mostrar.

      Guardar y cargar

      Elige un Save Mode en el manager: None, PlayerPrefs, JsonFile o Custom. Con Load On Awake y Auto Save activados (lo normal) no necesitas código. Se guardan los niveles y lo pagado en cada moneda, así los reembolsos son exactos. ToJson te deja meter el árbol en tu propio archivo de guardado.

      tree.Save();
      tree.Load();
      tree.DeleteSave();
      
      string json = tree.ToJson();
      tree.LoadFromJson(json);

      Almacenamiento propio

      using SkillTreeKit;
      using UnityEngine;
      
      public class CloudSkillStorage : MonoBehaviour, ISkillTreeStorage
      {
          public string Read(string key) => CloudSave.Get(key);
          public void Write(string key, string json) => CloudSave.Set(key, json);
          public void Delete(string key) => CloudSave.Remove(key);
      }

      Asígnalo al campo Storage del manager con el modo Custom, o llama a tree.SetStorage(storage, load: true).

      Reembolsos y reinicios

      Activa Allow Refunds y elige un Refund Ratio (1 = devuelve el precio completo). En el árbol, clic derecho sobre un nodo comprado reembolsa un nivel. ResetTree(true) reinicia todo el árbol.

      if (tree.CanRefund("power_2") == SkillRefundResult.Success)
          tree.TryRefund("power_2");
      
      tree.ResetTree(refund: true);
      • Required: otro nodo comprado depende de este; reembólsalo primero.
      • Disabled: los reembolsos están desactivados en el manager.
      • NotOwned: no hay nada que reembolsar.

      Eventos

      Eventos del manager

      tree.NodePurchased  += node => Analytics.Log("skill", node.id);
      tree.LevelChanged   += (node, level) => { };
      tree.NodeRefunded   += (node, level) => { };
      tree.PurchaseFailed += (node, result) => { };
      tree.StatsChanged   += RefreshPlayer;
      tree.FlagAdded      += flag => { };
      tree.TreeReset      += () => { };
      tree.Loaded         += () => { };

      Los mismos momentos están también como UnityEvents en el manager (onNodeLeveled, onNodeRefunded, onPurchaseFailed, onTreeReset, onTreeChanged).

      Eventos de la vista

      SkillTreeView informa de lo que ve el jugador: NodeHovered, NodeClicked, SelectionChanged, NodeRevealed, NodeStateChanged, NodeLeveled, NodeFailed y NodeCustomStateChanged. Añade SkillViewEvents para conectarlos desde el inspector, con un filtro opcional por id de nodo.

      Personalizar la interfaz

      Todo lo siguiente está en el Style de la vista y en la pestaña Apariencia, donde los cambios se ven al momento en la preview.

      Colores por estado

      Por defecto los nodos usan el color de su rama. Activa customStateColors para elegir colores de relleno, borde e icono para Disponible, Sin dinero, Comprado y Bloqueado, y customLineColors para las líneas.

      Formas y sprites

      Las formas de los nodos vienen de los tipos de nodo. Para tu propio arte, usa backgroundSprite, boardSprite y los sprites de borde y relleno de cada tipo; se tiñen según el estado. Desactiva drawBackground y showFrame para dibujar sobre tu propio canvas.

      Líneas

      • linkRouting: Curve u Orthogonal.
      • dashedLines, showArrows, showLineFlow.
      • arrowSprite y lineSprite (textura repetida con velocidad de desplazamiento).
      • linkRenderer: un asset SkillLinkRenderer que construye la malla de la línea.
      using SkillTreeKit.UI;
      using UnityEngine;
      
      [CreateAssetMenu(menuName = "Skill Tree/Bead Line")]
      public class BeadLinkRenderer : SkillLinkRenderer
      {
          public override void Draw(SkillLinkDrawContext context)
          {
              SkillLinkMesh.Strip(context.Mesh, context.Points, context.Width, context.Color);
              foreach (Vector2 point in context.Points)
                  SkillLinkMesh.Circle(context.Mesh, point, context.Width * 1.5f, context.Color);
          }
      }

      Clic y selección

      clickAction puede ser Purchase, Select o SelectThenPurchase. Usa view.Select(id), view.PurchaseSelected() y view.ClearSelection() para mando o botones propios. showAllNodes muestra los nodos bloqueados con un candado.

      Popup

      Crea un estilo (Create → Skill Tree → Popup Style): posición (Auto, Below, Above, Right, Left), tamaños, secciones, fuentes, colores, sprites, textos y animación. Crear plantilla en el editor de popup convierte el diseño en un prefab que puedes reorganizar; el estilo se le sigue aplicando. Desactiva Usar estilo en la plantilla para controlar su aspecto solo desde el prefab.

      Estados propios

      tree.customStates añade tus propios estados encima de los del kit, cada uno con colores, insignia y pulso. Reglas: Manual, ReadyToBuy, NotEnoughCurrency, PartiallyLeveled, Maxed, NewlyAvailable y Flag. Los estados manuales se ponen desde código:

      view.SetNodeState("forge_1", "event_sale");
      view.ClearNodeState("forge_1");

      Animaciones

      style.animation agrupa los tiempos de aparición, compra, sacudida, hover, pulso y líneas, cada uno con duración y curva. Los tweens usan el reloj propio del kit, así que también se ven en las previews del editor.

      Animador de nodos propio

      Sustituye las animaciones del kit con un asset SkillNodeAnimator asignado a style.nodeAnimator. Sobrescribe solo los momentos que te interesen:

      using DG.Tweening;
      using SkillTreeKit.UI;
      using UnityEngine;
      
      [CreateAssetMenu(menuName = "Skill Tree/Spin Animator")]
      public class SpinAnimator : SkillNodeAnimator
      {
          public override Tween Purchase(SkillNodeAnimContext c)
          {
              SkillMotionLayer layer = c.Motion.Action;
              Tween t = Value(0f, 1f, 0.5f, Ease.OutBack, p => layer.rotation = 360f * p);
              t.OnKill(layer.Reset);
              return t;
          }
      }

      Hay un ejemplo completo en Examples/Scripts/BouncyNodeAnimator.cs.

      Audio

      Los sonidos se guardan en el árbol (tree.audio): compra, subir de nivel, nivel máximo, hito, sin dinero, bloqueado, reembolso, reinicio, hover y selección, cada uno con volumen y variación de tono. Comprar seguido sube el tono como un combo. Cada nodo puede tener su propio sonido de compra.

      Añade SkillTreeAudio al GameObject del manager para que suenen: grupo del mixer, volumen general, silencio, intervalo mínimo y número de voces.

      VFX

      tree.vfx asigna un efecto a cada evento: Purchase, LevelUp, MaxLevel, Milestone, Unlocked, Fail y Refund. Las formas incluidas (Burst, Ring, Sparkle, Confetti, Glow) se dibujan como mallas de UI, así que funcionan en Screen Space Overlay sin cámaras. Los prefabs con ParticleSystems se convierten solos en partículas de UI.

      using SkillTreeKit;
      using UnityEngine;
      
      [CreateAssetMenu(menuName = "Skill Tree/Shake Camera Vfx")]
      public class ShakeCameraVfx : SkillVfxEffect
      {
          public override void Play(SkillVfxContext context)
          {
              if (context.Event == SkillVfxEvent.Milestone) CameraShake.Play(0.3f);
          }
      }

      Idioma

      El kit está en inglés e incluye español. Las ventanas del editor cambian con el selector EN/ES. En el juego, los textos que genera el kit (descripciones de efectos, panel de debug) siguen a SkillText.Language:

      SkillText.Language = SkillLanguage.Spanish;
      SkillText.Changed += RefreshMyTexts;

      Referencia de la API pública

      Encontrar un árbol

      Main es el primer manager de la escena; Find busca uno por SkillTreeAsset.treeId.

      SkillTreeManager.Main
      SkillTreeManager.Find("tree_id")

      Consultas

      int  GetLevel(string id)
      int  GetMaxLevel(string id)
      bool IsOwned(string id)
      bool IsMaxed(string id)
      bool IsAvailable(string id)
      bool IsVisible(string id)
      SkillNodeState GetState(string id)
      IReadOnlyList<string> GetNeighbors(string id)
      IEnumerable<string> OwnedIds

      Compras y niveles

      Unlock da un nodo gratis.

      SkillPurchaseCheck  Check(string id)
      SkillPurchaseCheck  Purchase(string id)
      SkillPurchaseResult TryPurchase(string id)
      void Unlock(string id)
      void SetLevel(string id, int level)
      int  PurchaseAllAvailable(bool free)

      Costos y monedas

      long GetCost(string id)
      long GetLevelCost(string id, int level)
      void GetCosts(string id, List<SkillCostEntry> into)
      long GetTotalTreeCost()
      long GetRemainingCost()
      long Spent
      void RegisterCurrency(string currencyId, ISkillCurrency source)

      Stats y flags

      float GetStat(string statId, float defaultValue = 0f)
      float GetStatMax(string statId)
      bool  HasFlag(string flagId)
      void  SetFlag(string flagId, bool value)
      void  Refresh()

      Forma recomendada de integrarlo

      1. Un SkillTreeAsset por pantalla de progresión; el asset es diseño, no datos de partida.
      2. Nombra los stats por su significado (dmg, spd) y deja que el árbol los sume.
      3. Lee los stats con componentes de conexión o con StatsChanged, no en cada frame.
      4. Implementa ISkillCurrency en tu monedero en lugar de copiar saldos.
      5. Pon las reglas propias del juego en validadores, no en el asset del árbol.
      6. Prueba los precios en la ventana Preview (Comprar todo, multiplicador de costos) antes de balancear en Play.

      Qué incluye

      Escenas de ejemplo

      • PopupExample: árbol radial de 15 nodos, plantilla de popup, caja de dinero, panel de debug.
      • SidePanelExample: árbol plano de 33 nodos, prefab de panel de detalle, HUD de stats, flags de habilidades y VFX al subir de nivel.

      Scripts de ejemplo

      • SkillTreeExampleToggle: Tab abre y cierra el árbol, Esc lo cierra.
      • SkillHudRow, SkillBalanceText: textos de HUD que destellan al cambiar.
      • BouncyNodeAnimator, WavyLinkRenderer, FloatingTextVfx, SkillParticleTint.

      Herramientas de editor

      • Ventanas Home, Tree Editor, Preview y Popup.
      • Generadores de ejemplos en Tools → Skill Tree → Examples.
      • SkillTreeDebug: panel en el juego con totales, barra de progreso, reiniciar y comprar todo.

      Solución de problemas

      El kit no compila

      Falta DOTween. Impórtalo desde la Asset Store y ejecuta su configuración una vez.

      El árbol sale vacío en Play

      • La vista no tiene manager asignado, o el manager no tiene árbol.
      • El árbol no tiene nodo raíz. Revisa la pestaña Validar.

      Un nodo no se puede comprar

      • Muestra tree.Check(id) en la consola: el resultado y Reason te dicen qué regla falla.
      • Los hitos necesitan todos sus vecinos; cambia prerequisiteMode si no es lo que quieres.
      • Una moneda extra no tiene ninguna fuente registrada.

      El progreso no se guarda

      Revisa Save Mode y Auto Save. Dos managers con la misma Save Key se pisan entre sí; dale a cada uno su propia clave.

      Un stat no cambia nada en el juego

      Abre el nodo en el editor: si En el juego dice Sin conexión, pulsa + para crear un SkillStatBinding y elige tu setter.

      Los iconos no se ven

      El shader de iconos usa la luminancia de la imagen como máscara. Usa iconos oscuros con transparencia; los iconos blancos puros desaparecen al teñirse.

      Las partículas no salen en el canvas

      Deja activado vfx.particlesInUI. Los prefabs con ParticleSystems solo se dibujan como UI con esa opción activada.

      Soporte y comentarios

      ¿Encontraste un error o te falta algo? Escríbeme con tu versión de Unity, una descripción corta y, si puedes, una captura de la pestaña Validar.

      © 2026 Eduardo Castro Skill Tree Kit v1.0.0