unity-performance-and-gc
БесплатноБез исполняемых скриптовНе проверенUse when touching Unity per-frame code, spawning, physics queries, UI updates or rendering setup - profiling with numbers, zero-GC hot paths (caching…
от makifbaysal★ 123 звезды на GitHubОб этом скилле
Unity Performance and GC
Overview
Unity's managed heap is garbage-collected; every allocation in Update is a future GC spike, and the incremental collector only spreads the pain. Most frame drops in Unity projects come from a short list: allocations per frame, per-frame lookups, unpooled spawning, physics queries that allocate, UI rebuilds, and draw calls. Find which one with the Profiler, fix it, and prove the fix with numbers (game-performance-budget).
Core principle: Zero managed allocations per frame in gameplay, measured — not assumed — with the Profiler's GC Alloc column or an allocation test.
Profile first
- Profiler: CPU Usage (Hierarchy, sort by Time ms and GC Alloc), Rendering, Physics, Memory modules. Profile a Development Build with Autoconnect; the Editor adds overhead.
- Deep Profile only to locate a call, never for timing.
- Profile Analyzer compares a before and an after capture; Memory Profiler finds leaks across scene loads.
- Mark your own code:
static readonly ProfilerMarker s_Marker = new("Enemy.Think"); using (s_Marker.Auto()) { ... }.
The allocation list
// ❌ allocates or searches every frame
void Update() {
var enemies = FindObjectsByType<Enemy>(FindObjectsSortMode.None); // array + scene search
var close = enemies.Where(e => (e.transform.position - transform.position).sqrMagnitude < r2).ToList(); // LINQ + closure
hpText.text = "HP: " + hp; // new string every frame
if (other.tag == "Enemy") { } // allocates the tag string
var hits = Physics.OverlapSphere(transform.position, 5f); // new array per call
StartCoroutine(Flash(new WaitForSeconds(0.1f))); // allocation per call
}
// ✅ cached, reused, non-allocating
readonly Collider[] _hits = new Collider[32];
static readonly WaitForSeconds FlashDelay = new(0.1f);
int _shownHp = -1;
void Update() {
int count = Physics.OverlapSphereNonAlloc(transform.position, 5f, _hits, enemyMask);
for (int i = 0; i < count; i++) { /* use _hits[i] */ }
if (hp != _shownHp) { _shownHp = hp; hpText.SetText("HP: {0}", hp); } // TextMeshPro, no string alloc
if (other.CompareTag("Enemy")) { }
}
More of the same:
- 3D queries:
RaycastNonAlloc,SphereCastNonAlloc,OverlapBoxNonAlloc. 2D: the overloads taking aContactFilter2Dand a reusedList<T>/array (the 2D*NonAllocmethods are obsolete). GetComponentsInChildren(list)overloads that fill a reused list.Animator.StringToHash,Shader.PropertyToID, cachedWaitForSeconds/WaitForFixedUpdate.foreachoverList<T>and arrays is fine; over anIEnumerable<T>interface it boxes the enumerator.- No capturing lambdas,
string.Format/interpolation,paramsarrays or boxing (struct →object/interface) in hot paths. Debug.Login a hot path allocates and stalls — strip it from builds ([Conditional("UNITY_EDITOR")]wrapper) or remove it.Camera.mainis cheaper than it was but is still a lookup — cache it.
Pool what you spawn
using UnityEngine.Pool;
public sealed class BulletSpawner : MonoBehaviour {
[SerializeField] Bullet prefab;
ObjectPool<Bullet> _pool;
void Awake() => _pool = new ObjectPool<Bullet>(
createFunc: () => { var b = Instantiate(prefab); b.Init(release: x => _pool.Release(x)); return b; },
actionOnGet: b => b.gameObject.SetActive(true),
actionOnRelease: b => b.gameObject.SetActive(false),
actionOnDestroy: b => Destroy(b.gameObject),
collectionCheck: false, defaultCapacity: 64, maxSize: 256);
public void Fire(Vector3 pos, Vector3 dir) { var b = _pool.Get(); b.Launch(pos, dir); }
}
Pre-warm at load (get and release defaultCapacity instances) so the first fight does not instantiate. A pooled object resets all its state in actionOnGet/Launch, not in Start.
Prove zero allocations
using Is = UnityEngine.TestTools.Constraints.Is;
[Test] public void Tick_SteadyState_DoesNotAllocate() {
var sim = TestSim.WithEnemies(100);
sim.Tick(0.016f); // warm-up: first call may JIT/initialise
Assert.That(() => sim.Tick(0.016f), Is.Not.AllocatingGCMemory());
}
Burst and Jobs for bulk work
For the same math over hundreds or thousands of items (flocking, projectiles, terrain), a Burst-compiled job on native containers:
[BurstCompile]
struct MoveJob : IJobParallelFor {
public NativeArray<float3> Positions;
[ReadOnly] public NativeArray<float3> Velocities;
public float Dt;
public void Execute(int i) => Positions[i] += Velocities[i] * Dt;
}
// schedule: var h = new MoveJob { ... }.Schedule(count, 64); later h.Complete();
- Native containers are disposed (
Allocator.PersistentinOnDestroy;TempJobwithin four frames;Tempwithin the frame). - Complete handles before reading results; sch
Установить unity-performance-and-gc в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл unity-performance-and-gc?
Use when touching Unity per-frame code, spawning, physics queries, UI updates or rendering setup - profiling with numbers, zero-GC hot paths (caching, NonAlloc queries, no LINQ/closures/boxing, TMP SetText), ObjectPool, allocation tests, Burst/Jobs for bulk math, and rendering/physics settings that cost frames.
Как установить скилл unity-performance-and-gc?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл unity-performance-and-gc запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic