Token导航 LogoToken导航TokenDH.com
研究检索只读github未标认证来源可访问clear审计通过

unity-performanceUnity 性能

Agent Skill

unity-performance 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

23,942

周安装

647

GitHub Stars

3

下载量

7,235
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:unity-performance(Unity 性能)
来源仓库:https://github.com/cryptorabea/claude_unity_dev_plugin
仓库路径:skills/unity-performance
安装命令:
npx skills add https://github.com/cryptorabea/claude_unity_dev_plugin --skill 'Unity Performance'
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/cryptorabea/claude_unity_dev_plugin --skill 'Unity Performance'

简介

unity-performance 用于查找、检索和筛选相关信息。

  • 适合在 Codex、Claude、Cursor、Gemini CLI 中根据关键词或任务场景快速定位候选结果。
  • 支持性能分析、调试工具等 Unity 开发相关内容检索。
  • 安装前需确认权限范围、维护状态及是否触发联网或命令执行。
  • 建议结合原始 README 核验具体功能与使用边界。

SKILL.md

Unity Performance Optimization

Essential performance optimization techniques for Unity games, covering memory management, CPU optimization, rendering, and profiling strategies.

Overview

Performance is critical for Unity games across all platforms. Poor performance manifests as low framerates, stuttering, long load times, and crashes. This skill covers proven optimization techniques that apply to all Unity projects.

Core optimization areas:

  • CPU optimization (Update loops, caching, pooling)
  • Memory management (GC reduction, allocation patterns)
  • Rendering optimization (batching, culling, LOD)
  • Profiling and measurement (identifying bottlenecks)

Reference Caching

The most common Unity performance mistake is repeated expensive lookups. Cache all references to avoid redundant operations.

GetComponent Caching

Never call GetComponent repeatedly - cache results in Awake:

// ❌ BAD - GetComponent every frame
private void Update()
{
    GetComponent<Rigidbody>().velocity = Vector3.forward;  // SLOW!
}

// ✅ GOOD - Cache once
private Rigidbody rb;

private void Awake()
{
    rb = GetComponent<Rigidbody>();
}

private void Update()
{
    rb.velocity = Vector3.forward;  // FAST
}

Performance impact: GetComponent is 10-100x slower than cached reference.

Transform Caching

Cache transform access, especially for frequently accessed GameObjects:

// ❌ BAD - Property access overhead
private void Update()
{
    transform.position += Vector3.forward * Time.deltaTime;
    transform.rotation = Quaternion.identity;
}

// ✅ GOOD - Cache transform reference
private Transform myTransform;

private void Awake()
{
    myTransform = transform;
}

private void Update()
{
    myTransform.position += Vector3.forward * Time.deltaTime;
    myTransform.rotation = Quaternion.identity;
}

Why: transform property has overhead. Cached reference eliminates repeated lookups.

Find Method Caching

Never use Find methods in Update - cache results:

// ❌ BAD - Find every frame (EXTREMELY SLOW)
private void Update()
{
    GameObject player = GameObject.Find("Player");
    Transform target = GameObject.FindWithTag("Enemy").transform;
}

// ✅ GOOD - Cache in Start
private GameObject player;
private Transform target;

private void Start()
{
    player = GameObject.Find("Player");
    target = GameObject.FindWithTag("Enemy")?.transform;
}

private void Update()
{
    // Use cached references
}

Performance impact: Find methods scan entire scene hierarchy. 100-1000x slower than cached references.

Material Caching

Access renderer.material creates new Material instance - cache to avoid leaks:

// ❌ BAD - Creates new Material every frame (MEMORY LEAK)
private void Update()
{
    GetComponent<Renderer>().material.color = Color.red;  // Creates new Material!
}

// ✅ GOOD - Cache material reference
private Material material;

private void Awake()
{
    material = GetComponent<Renderer>().material;
}

private void Update()
{
    material.color = Color.red;  // Modifies cached Material
}

private void OnDestroy()
{
    // Clean up instantiated material
    if (material != null)
        Destroy(material);
}

Critical: Accessing .material creates new instance. Use .sharedMaterial for read-only access to avoid instantiation.

Object Pooling

Instantiate and Destroy are expensive. Reuse objects instead of creating/destroying repeatedly.

Basic Pool Implementation

public class ObjectPool : MonoBehaviour
{
    [SerializeField] private GameObject prefab;
    [SerializeField] private int initialSize = 10;

    private Queue<GameObject> pool = new Queue<GameObject>();

    private void Awake()
    {
        // Pre-instantiate objects
        for (int i = 0; i < initialSize; i++)
        {
            GameObject obj = Instantiate(prefab);
            obj.SetActive(false);
            pool.Enqueue(obj);
        }
    }

    public GameObject Get()
    {
        if (pool.Count > 0)
        {
            GameObject obj = pool.Dequeue();
            obj.SetActive(true);
            return obj;
        }

        // Pool exhausted - create new
        return Instantiate(prefab);
    }

    public void Return(GameObject obj)
    {
        obj.SetActive(false);
        pool.Enqueue(obj);
    }
}

Use for:

  • Bullets, projectiles
  • Particle effects
  • UI elements (tooltips, damage numbers)
  • Enemies in wave-based games
  • Audio sources

Performance gain: 10-50x faster than Instantiate/Destroy, eliminates GC spikes.

Pool Pattern Usage

public class BulletSpawner : MonoBehaviour
{
    [SerializeField] private ObjectPool bulletPool;
    [SerializeField] private Transform firePoint;

    private void Fire()
    {
        // Get from pool
        GameObject bullet = bulletPool.Get();
        bullet.transform.position = firePoint.position;
        bullet.transform.rotation = firePoint.rotation;

        // Return after 3 seconds
        StartCoroutine(ReturnToPoolAfterDelay(bullet, 3f));
    }

    private IEnumerator ReturnToPoolAfterDelay(GameObject obj, float delay)
    {
        yield return new WaitForSeconds(delay);
        bulletPool.Return(obj);
    }
}

Update Loop Optimization

Update, FixedUpdate, and LateUpdate are called frequently - minimize work done in these methods.

Remove Empty Update Methods

// ❌ BAD - Empty methods still have overhead
private void Update() { }
private void FixedUpdate() { }

// ✅ GOOD - Remove unused methods
// (No Update/FixedUpdate if not needed)

Performance: Unity calls all Update methods even if empty. Remove to reduce overhead.

Reduce Update Frequency

Not all logic needs to run every frame:

// ❌ BAD - Expensive check every frame
private void Update()
{
    CheckForNearbyEnemies();  // Expensive raycast/distance checks
}

// ✅ GOOD - Check every N frames
private int frameCounter = 0;
private const int checkInterval = 10;

private void Update()
{
    frameCounter++;
    if (frameCounter >= checkInterval)
    {
        frameCounter = 0;
        CheckForNearbyEnemies();
    }
}

// ✅ BETTER - Use InvokeRepeating or Coroutine
private void Start()
{
    InvokeRepeating(nameof(CheckForNearbyEnemies), 0f, 0.2f);  // Every 0.2 seconds
}

Alternative: Coroutines

private void Start()
{
    StartCoroutine(CheckEnemiesRoutine());
}

private IEnumerator CheckEnemiesRoutine()
{
    while (true)
    {
        CheckForNearbyEnemies();
        yield return new WaitForSeconds(0.2f);
    }
}

Event-Driven Architecture

Replace polling with events:

// ❌ BAD - Poll for state change every frame
private bool wasGrounded;

private void Update()
{
    bool grounded = IsGrounded();
    if (grounded != wasGrounded)
    {
        OnGroundedChanged(grounded);
    }
    wasGrounded = grounded;
}

// ✅ GOOD - Event-driven
public event Action<bool> OnGroundedChanged;

private bool isGrounded;

private void SetGrounded(bool grounded)
{
    if (isGrounded != grounded)
    {
        isGrounded = grounded;
        OnGroundedChanged?.Invoke(grounded);
    }
}

Garbage Collection Reduction

Avoid allocations in frequently-called methods to prevent GC spikes.

String Concatenation

// ❌ BAD - Allocates strings every frame
private void Update()
{
    string message = "Health: " + health;  // String allocation
    scoreText.text = "Score: " + score;    // String allocation
}

// ✅ GOOD - Use StringBuilder or string interpolation
private StringBuilder sb = new StringBuilder();

private void UpdateUI()
{
    sb.Clear();
    sb.Append("Health: ").Append(health);
    healthText.text = sb.ToString();
}

// ✅ ALTERNATIVE - Cache formatted strings
private void UpdateHealth(int newHealth)
{
    health = newHealth;
    healthText.text = health.ToString();  // Less allocation than concatenation
}

Collection Allocation

// ❌ BAD - Allocates new list every frame
private void Update()
{
    List<Enemy> nearbyEnemies = new List<Enemy>();  // GC allocation!
    FindNearbyEnemies(nearbyEnemies);
}

// ✅ GOOD - Reuse list
private List<Enemy> nearbyEnemies = new List<Enemy>();

private void Update()
{
    nearbyEnemies.Clear();  // Reuse existing list
    FindNearbyEnemies(nearbyEnemies);
}

Array/List Best Practices

// ❌ BAD - ToArray allocates
private void Update()
{
    GameObject[] enemies = enemyList.ToArray();  // GC allocation!
}

// ✅ GOOD - Iterate list directly
private void Update()
{
    for (int i = 0; i < enemyList.Count; i++)
    {
        Enemy enemy = enemyList[i];
        // Process enemy
    }
}

// ✅ GOOD - Use foreach (no allocation for List)
private void Update()
{
    foreach (var enemy in enemyList)
    {
        // Process enemy
    }
}

Coroutine Allocation

// ❌ BAD - Allocates WaitForSeconds every call
private IEnumerator DelayedAction()
{
    yield return new WaitForSeconds(1f);  // New allocation each time
}

// ✅ GOOD - Cache WaitForSeconds
private WaitForSeconds oneSecondWait = new WaitForSeconds(1f);

private IEnumerator DelayedAction()
{
    yield return oneSecondWait;  // Reuse cached wait
}

Component Access Patterns

Minimize Component Queries

// ❌ BAD - Multiple GetComponent calls
private void OnTriggerEnter(Collider other)
{
    if (other.GetComponent<Enemy>() != null)
    {
        other.GetComponent<Enemy>().TakeDamage(10);  // Called twice!
    }
}

// ✅ GOOD - Single GetComponent with pattern matching
private void OnTriggerEnter(Collider other)
{
    if (other.TryGetComponent<Enemy>(out var enemy))
    {
        enemy.TakeDamage(10);  // Called once
    }
}

Component Caching for Collisions

// ❌ BAD - GetComponent on every collision
private void OnTriggerEnter(Collider other)
{
    var damageable = other.GetComponent<IDamageable>();
    if (damageable != null)
        damageable.TakeDamage(10);
}

// ✅ GOOD - Cache component on trigger enter
private Dictionary<Collider, IDamageable> damageableCache = new Dictionary<Collider, IDamageable>();

private void OnTriggerEnter(Collider other)
{
    if (!damageableCache.TryGetValue(other, out var damageable))
    {
        damageable = other.GetComponent<IDamageable>();
        damageableCache[other] = damageable;  // Cache for future collisions
    }

    damageable?.TakeDamage(10);
}

private void OnTriggerExit(Collider other)
{
    damageableCache.Remove(other);  // Clean up cache
}

Physics Optimization

Layer-Based Collision

Configure Physics Layer Collision Matrix to prevent unnecessary collision checks:

Edit > Project Settings > Physics > Layer Collision Matrix

// Setup layers
Layer 8: Player
Layer 9: Enemies
Layer 10: Projectiles
Layer 11: Environment

// Disable unnecessary collisions:
- Player vs Player (disabled)
- Enemies vs Enemies (disabled)
- Projectiles vs Projectiles (disabled)

Performance gain: 30-50% reduction in physics overhead.

Raycast Optimization

// ❌ BAD - Raycast checks everything
bool hit = Physics.Raycast(origin, direction, out RaycastHit hitInfo);

// ✅ GOOD - Layer mask limits checks
int layerMask = 1 << LayerMask.NameToLayer("Enemy");
bool hit = Physics.Raycast(origin, direction, out RaycastHit hitInfo, maxDistance, layerMask);

// ✅ BETTER - Cache layer mask
private int enemyLayerMask;

private void Awake()
{
    enemyLayerMask = 1 << LayerMask.NameToLayer("Enemy");
}

private void Fire()
{
    bool hit = Physics.Raycast(origin, direction, out RaycastHit hitInfo, maxDistance, enemyLayerMask);
}

Rigidbody Sleep

Let Rigidbody sleep when not moving:

// Rigidbody automatically sleeps when velocity < threshold
// Configure in Edit > Project Settings > Physics

// Wake up manually when needed
private void ApplyForce()
{
    if (rb.IsSleeping())
        rb.WakeUp();

    rb.AddForce(force);
}

Profiling

Measure before optimizing. Use Unity Profiler to identify actual bottlenecks.

Open Profiler: Window > Analysis > Profiler

Key Profiler Metrics

CPU Usage:

  • Rendering (DrawCalls, SetPass calls)
  • Scripts (Update, FixedUpdate, Coroutines)
  • Physics (FixedUpdate.PhysicsFixedUpdate)
  • GC.Alloc (garbage collection allocations)

Memory:

  • Total Allocated
  • GC Allocated
  • Texture memory
  • Mesh memory

Profiling Workflow

  1. Identify bottleneck: Run Profiler, find expensive frame
  2. Drill down: Click spike, view call hierarchy
  3. Measure baseline: Record current performance
  4. Apply optimization: Make targeted changes
  5. Measure improvement: Compare before/after
  6. Repeat: Find next bottleneck

Deep Profile

Enable Deep Profile for detailed call stack (impacts performance):

Warning: Deep Profile slows game significantly. Use for small scenes or targeted profiling.

Custom Profiler Markers

Measure specific code sections:

using Unity.Profiling;

public class AIController : MonoBehaviour
{
    private static readonly ProfilerMarker s_PathfindingMarker = new ProfilerMarker("AI.Pathfinding");
    private static readonly ProfilerMarker s_DecisionMarker = new ProfilerMarker("AI.DecisionMaking");

    private void Update()
    {
        s_PathfindingMarker.Begin();
        CalculatePath();
        s_PathfindingMarker.End();

        s_DecisionMarker.Begin();
        MakeDecision();
        s_DecisionMarker.End();
    }

    private void CalculatePath() { }
    private void MakeDecision() { }
}

Shows custom markers in Profiler for precise measurement.

Performance Budgets

Set performance targets for each system:

Target: 60 FPS (16.67ms per frame)

  • Rendering: 6ms
  • Scripts: 4ms
  • Physics: 2ms
  • UI: 1ms
  • Audio: 0.5ms
  • Other: 3ms

Monitor with Profiler and optimize systems exceeding budget.

Platform-Specific Optimization

Mobile Optimization

Key concerns:

  • Lower CPU/GPU power
  • Memory constraints
  • Battery life
  • Touch input overhead

Mobile-specific optimizations:

  • Reduce draw calls (<100 for mobile)
  • Lower texture resolution
  • Disable shadows or use simple shadows
  • Reduce particle count
  • Use occlusion culling
  • Optimize UI (Canvas batching)

PC/Console Optimization

More headroom but still optimize:

  • Target 60 FPS minimum
  • Allow higher quality settings
  • Monitor VRAM usage
  • Profile on minimum spec hardware

Additional Resources

Reference Files

For detailed performance techniques, consult:

  • references/memory-optimization.md - Advanced GC reduction, allocation patterns
  • references/rendering-optimization.md - Draw call batching, GPU optimization, shaders
  • references/physics-optimization.md - Collision optimization, Rigidbody best practices
  • references/profiling-guide.md - Complete profiling workflows, tools, analysis

Quick Reference

Caching priorities:

  1. Transform references
  2. GetComponent results
  3. Find results
  4. Material instances
  5. WaitForSeconds in coroutines

Avoid in Update:

  • GetComponent
  • Find methods
  • String concatenation
  • New allocations
  • Physics raycasts (use sparingly)

Always profile before optimizing:

  • Measure baseline
  • Identify bottleneck
  • Apply targeted fix
  • Measure improvement

Apply these performance practices consistently for smooth, responsive Unity games across all platforms.

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

28.93%
按下载量换算2,093

Antigravity

21.09%
按下载量换算1,526

windsurf

17.32%
按下载量换算1,253

OpenCode

11.75%
按下载量换算850

Codex

8.44%
按下载量换算611

Gemini CLI

3.56%
按下载量换算258

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

只读

该 Skill 主要提供规则、说明或参考内容,本身偏只读;真正读写文件、联网或执行命令仍取决于宿主 Agent 的任务。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源字段存在多来源差异,先按来源优先级自动处理,无法消解时进入异常复核队列。

来源信息

继续浏览同类 Skills