Unity Scripting 标志

Unity Scripting

组织
Nice-Wolf-Studio
unity-scripting

Unity 6 C# scripting guide. Use when writing MonoBehaviour scripts, handling lifecycle events (Awake, Start, Update, FixedUpdate), using coroutines or async/await (Awaitable), working with ScriptableObjects, events, delegates, or core APIs like Vector3, Quaternion, Time, Debug. Based on Unity 6.3 LTS documentation.

概览

发布者Nice-Wolf-Studio
代码仓库unity-claude-skills
技能名称unity-scripting
星标数
40
复刻数
5
附带文件
4
许可协议MIT
链接
  • Markdown 格式的指令

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

  • 兼容任何大语言模型

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

  • 4 个随附文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 Nice-Wolf-Studio 发布于 GitHub。请在安装前查看源内容。

安装

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

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/Nice-Wolf-Studio/unity-claude-skills/tree/main/skills/unity-scripting
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

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

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Nice-Wolf-Studio/unity-claude-skills.git /tmp/unity-claude-skills
mkdir -p .claude/skills
cp -r /tmp/unity-claude-skills/skills/unity-scripting .claude/skills/unity-scripting
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

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

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

兼容任何 AI 模型

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

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会获取指令,因此未使用的技能不会产生额外费用。

  • 在聊天中切换模型

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

技能指令

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

Unity C# Scripting

Script Fundamentals

C# scripts (.cs files) are stored in the Assets folder. Scripts gain Unity functionality by inheriting from built-in types:

  • UnityEngine.Object -- Makes custom types assignable to Inspector fields
  • MonoBehaviour -- Attaches to GameObjects as components to control behavior in a scene
  • ScriptableObject -- Standalone data assets not attached to GameObjects

Scripts operate in two contexts:

  • Runtime scripts -- Execute in the Player build (use UnityEngine namespace)
  • Editor scripts -- Run only in the Editor (use UnityEditor namespace, place in Editor folders)

MonoBehaviour Lifecycle

MonoBehaviours always exist as a Component of a GameObject. The lifecycle event functions execute in a strict order. You cannot rely on the order in which the same event function is invoked for different GameObjects unless configured via Script Execution Order settings.

Execution Order (ASCII Diagram)

INITIALIZATION
  |
  v
[Awake] ---------> Called when script instance loads (once per lifetime)
  |
  v
[OnEnable] ------> Called when object/component becomes enabled
  |
  v
(SceneManager.sceneLoaded fires here -- after OnEnable, before Start)
  |
  v
[Start] ---------> Called before first frame Update (once per lifetime)
  |
  |
  |  +===========================================+
  |  |          PHYSICS LOOP (fixed timestep)    |
  |  |                                           |
  +->| [FixedUpdate] --> Internal Physics ------>|
  |  |       |                                   |
  |  | [yield WaitForFixedUpdate resumes]        |
  |  +===========================================+
  |
  v
[Update] --------> Called once per frame
  |
  v
[yield null / yield WaitForSeconds resumes]
  |
  v
(Internal Animation Update)
  |   [OnAnimatorMove]
  |   [OnAnimatorIK]
  |
  v
[LateUpdate] ----> Called after all Update functions complete
  |
  v
RENDERING
  | [OnWillRenderObject]
  | [OnPreCull] [OnBecameVisible/Invisible]
  | [OnPreRender]
  | [OnRenderObject]
  | [OnPostRender]
  | [OnRenderImage]
  |
  v
[OnGUI] ---------> Called for GUI rendering events
  |
  v
[yield WaitForEndOfFrame resumes]
  |
  v
DEACTIVATION / TEARDOWN
  |
  v
[OnDisable] -----> Called when component/object is disabled
  |
  v
[OnDestroy] -----> Called before object destruction

Key Lifecycle Callbacks

CallbackTimingUse For
Awake()Script instance loadsOne-time init, cache references
OnEnable()Component enabledSubscribe to events
Start()Before first UpdateInit that depends on other Awake() calls
FixedUpdate()Fixed timestep (default 0.02s)Physics calculations, Rigidbody forces
Update()Every frameInput, non-physics game logic
LateUpdate()After all Update callsCamera follow, post-Update adjustments
OnDisable()Component disabledUnsubscribe from events
OnDestroy()Before destructionFinal cleanup

Physics Callbacks

csharp
// 3D Physics
void OnCollisionEnter(Collision collision) { }
void OnCollisionStay(Collision collision) { }
void OnCollisionExit(Collision collision) { }
void OnTriggerEnter(Collider other) { }
void OnTriggerStay(Collider other) { }
void OnTriggerExit(Collider other) { }

// 2D Physics
void OnCollisionEnter2D(Collision2D collision) { }
void OnTriggerEnter2D(Collider2D other) { }

MonoBehaviour Properties (Unity 6)

PropertyPurpose
destroyCancellationTokenToken raised when MonoBehaviour is destroyed (for async cancellation)
didAwakeWhether Awake has been called
didStartWhether Start has been called
runInEditModeAllow script execution in editor

Full lifecycle reference: references/monobehaviour-lifecycle.md

Coroutines vs Async/Await

Unity supports two patterns for operations spanning multiple frames.

Coroutines (IEnumerator)

Methods that suspend with yield return and resume based on the yield instruction.

csharp
IEnumerator Fade()
{
    Color c = renderer.material.color;
    for (float alpha = 1f; alpha >= 0; alpha -= 0.1f)
    {
        c.a = alpha;
        renderer.material.color = c;
        yield return new WaitForSeconds(0.1f);
    }
}

void Update()
{
    if (Input.GetKeyDown("f"))
    {
        StartCoroutine(Fade());
    }
}

Yield Instructions:

  • yield return null -- Resume next frame (after Update)
  • yield return new WaitForSeconds(t) -- Resume after t seconds
  • yield return new WaitForFixedUpdate() -- Resume after FixedUpdate
  • yield return new WaitForEndOfFrame() -- Resume after rendering
  • yield return new WaitUntil(() => condition) -- Resume when condition is true
  • yield return StartCoroutine(other) -- Wait for nested coroutine

Important: Coroutines run on the main thread. Disabling the MonoBehaviour via enabled = false does NOT stop coroutines. Deactivating the GameObject or destroying the MonoBehaviour does stop them.

Awaitable (Unity 6 Async/Await)

Awaitable is Unity's custom async type -- usually more efficient than iterator-based coroutines. It is pooled to limit allocations.

csharp
async Awaitable SampleSchedulingJobsForNextFrame()
{
    await Awaitable.EndOfFrameAsync();
    var jobHandle = ScheduleSomethingWithJobSystem();
    await Awaitable.NextFrameAsync();
    jobHandle.Complete();
}

Awaitable Methods:

  • Awaitable.NextFrameAsync() -- Resume next frame
  • Awaitable.FixedUpdateAsync() -- Resume at next FixedUpdate
  • Awaitable.EndOfFrameAsync() -- Resume at end of frame
  • Awaitable.WaitForSecondsAsync(float) -- Resume after delay
  • Awaitable.MainThreadAsync() -- Force continuation on main thread
  • Awaitable.BackgroundThreadAsync() -- Force continuation on background thread

Critical constraint: Awaitable instances are pooled -- never await the same instance more than once. Multiple awaits cause undefined behavior.

FeatureCoroutineAwaitable
Return valuesNoYes (Awaitable<T>)
Thread switchingNoYes
Memory allocationPer-yield overheadPooled, minimal
CancellationManual StopCoroutineCancellationToken support
Error handlingNo try/catchFull try/catch/finally

Full async reference: references/coroutines-and-async.md

Events and Communication Patterns

C# Events and Delegates

csharp
public class Health : MonoBehaviour
{
    public event System.Action<float> OnDamageTaken;
    public event System.Action OnDeath;

    private float _hp = 100f;

    public void TakeDamage(float amount)
    {
        _hp -= amount;
        OnDamageTaken?.Invoke(amount);
        if (_hp <= 0f)
            OnDeath?.Invoke();
    }
}

public class UIHealthBar : MonoBehaviour
{
    [SerializeField] private Health _health;

    void OnEnable()
    {
        _health.OnDamageTaken += HandleDamage;
    }

    void OnDisable()
    {
        _health.OnDamageTaken -= HandleDamage;
    }

    private void HandleDamage(float amount)
    {
        // Update UI
    }
}

UnityEvents (Inspector-assignable)

csharp
using UnityEngine.Events;

public class GameManager : MonoBehaviour
{
    public UnityEvent OnGameStart;
    public UnityEvent<int> OnScoreChanged;

    public void StartGame()
    {
        OnGameStart?.Invoke();
    }
}

ScriptableObject Event Channels

csharp
[CreateAssetMenu(menuName = "Events/Void Event Channel")]
public class VoidEventChannel : ScriptableObject
{
    private System.Action _onEventRaised;

    public void RaiseEvent()
    {
        _onEventRaised?.Invoke();
    }

    public void Subscribe(System.Action listener) => _onEventRaised += listener;
    public void Unsubscribe(System.Action listener) => _onEventRaised -= listener;
}

ScriptableObjects

ScriptableObjects are serializable Unity types derived from UnityEngine.Object. They exist as independent project assets, not attached to GameObjects. Use them for shared data, configuration, and event channels.

csharp
[CreateAssetMenu(fileName = "Data", menuName = "ScriptableObjects/SpawnManagerScriptableObject", order = 1)]
public class SpawnManagerScriptableObject : ScriptableObject
{
    public string prefabName;
    public int numberOfPrefabsToCreate;
    public Vector3[] spawnPoints;
}

Key behaviors:

  • In Edit mode, Inspector modifications save automatically; script changes require EditorUtility.SetDirty()
  • At runtime, players can read ScriptableObject data but not persist modifications to disk
  • Memory efficient: multiple objects reference the same asset instance instead of duplicating data

Full ScriptableObject reference: references/scriptableobjects.md

Serialization Quick Reference

Unity serializes fields that meet ALL conditions:

  1. public OR has [SerializeField] attribute
  2. Not static, const, or readonly
  3. Is a serializable type

Serializable types: primitives, enums (32-bit or smaller), Unity built-in types (Vector2, Vector3, Rect, Color, AnimationCurve, etc.), [Serializable] custom classes/structs, UnityEngine.Object references, List<T> and arrays of any above type.

Key attributes:

csharp
[SerializeField] private float _speed = 5f;        // Serialize private field
[field: SerializeField] public float Speed { get; private set; } // Auto-property
[NonSerialized] public float tempValue;             // Exclude from serialization
[HideInInspector] public float hiddenValue;         // Serialize but hide from Inspector
[SerializeReference] private IMyInterface _impl;    // Polymorphic serialization

Not supported: Multidimensional arrays, jagged arrays, dictionaries, nested containers. Use ISerializationCallbackReceiver for custom serialization of unsupported types.

Core API Quick Reference

Vector3

csharp
// Static direction shortcuts
Vector3.zero;      // (0, 0, 0)
Vector3.one;       // (1, 1, 1)
Vector3.up;        // (0, 1, 0)
Vector3.forward;   // (0, 0, 1)
Vector3.right;     // (1, 0, 0)

// Common operations
float dist = Vector3.Distance(a, b);
float dot = Vector3.Dot(a.normalized, b.normalized);
Vector3 cross = Vector3.Cross(a, b);
Vector3 smoothed = Vector3.Lerp(from, to, t);
Vector3 moved = Vector3.MoveTowards(current, target, maxDelta);
Vector3 projected = Vector3.ProjectOnPlane(velocity, groundNormal);

Properties: magnitude, sqrMagnitude (use for comparisons -- avoids sqrt), normalized.

Quaternion

csharp
// Creation
Quaternion.identity;                             // No rotation
Quaternion.Euler(0f, 90f, 0f);                  // From Euler angles (degrees)
Quaternion.LookRotation(direction, Vector3.up);  // Face a direction
Quaternion.AngleAxis(45f, Vector3.up);           // Rotate around axis
Quaternion.FromToRotation(Vector3.up, normal);   // Rotation between directions

// Interpolation
Quaternion.Slerp(from, to, t);                  // Spherical interpolation
Quaternion.Lerp(from, to, t);                   // Linear interpolation

// Operations
float angle = Quaternion.Angle(a, b);           // Angle in degrees (0-180)
Vector3 rotatedPoint = rotation * point;         // Rotate a vector
Quaternion combined = rotA * rotB;               // Combine rotations

Never modify x, y, z, w directly. Use Euler(), AngleAxis(), or LookRotation().

Time

csharp
Time.deltaTime       // Seconds since last frame (use in Update)
Time.fixedDeltaTime  // Fixed timestep interval (use in FixedUpdate)
Time.time            // Time since game start
Time.timeScale       // 0 = paused, 1 = normal, 2 = double speed
Time.unscaledDeltaTime // Ignores timeScale (for UI animations during pause)

Debug

csharp
Debug.Log("Message");
Debug.LogWarning("Warning");
Debug.LogError("Error");
Debug.DrawRay(origin, direction, Color.red, duration);
Debug.DrawLine(start, end, Color.green, duration);

Common Patterns

Cached Component References

csharp
public class PlayerMovement : MonoBehaviour
{
    private Rigidbody _rb;
    private Transform _transform;

    void Awake()
    {
        _rb = GetComponent<Rigidbody>();
        _transform = transform; // Cache the transform property
    }

    void FixedUpdate()
    {
        // Use cached references -- never call GetComponent in Update/FixedUpdate
        _rb.AddForce(Vector3.up * 10f);
    }
}

Singleton Pattern

csharp
public class GameManager : MonoBehaviour
{
    public static GameManager Instance { get; private set; }

    void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
            return;
        }
        Instance = this;
        DontDestroyOnLoad(gameObject);
    }
}

Async with Cancellation (Unity 6)

csharp
public class AsyncExample : MonoBehaviour
{
    async void Start()
    {
        try
        {
            await LoadAndProcessAsync(destroyCancellationToken);
        }
        catch (OperationCanceledException) { }
    }

    async Awaitable LoadAndProcessAsync(CancellationToken token)
    {
        await Awaitable.BackgroundThreadAsync();
        // Heavy computation here (off main thread)
        var result = ComputeExpensiveData();

        await Awaitable.MainThreadAsync();
        // Back on main thread -- safe to use Unity API
        ApplyResult(result);
    }
}

Conditional Wait (Awaitable replacement for WaitUntil)

csharp
public static async Awaitable AwaitableUntil(Func<bool> condition, CancellationToken token)
{
    while (!condition())
    {
        token.ThrowIfCancellationRequested();
        await Awaitable.NextFrameAsync();
    }
}

Anti-Patterns

Anti-PatternProblemFix
GetComponent<T>() in Update()Allocates and searches every frameCache in Awake()
GameObject.Find() in Update()Expensive string search every frameCache reference or use serialized field
Repeated new Vector3() in hot pathsUnnecessary constructor overhead each frameUse Vector3.zero, Vector3.one, or cache reusable values
Modifying Quaternion.x/y/z/w directlyProduces invalid rotationsUse Euler(), AngleAxis(), LookRotation()
Physics logic in Update()Inconsistent at variable frameratesUse FixedUpdate() for Rigidbody forces
Time.deltaTime in FixedUpdate()Works (Unity returns fixedDeltaTime implicitly) but is unclear to readersUse Time.fixedDeltaTime explicitly for clarity
Forgetting to unsubscribe events in OnDisableMemory leaks, null reference errorsAlways unsubscribe in OnDisable()
await-ing same Awaitable twiceUndefined behavior (pooled instances)Await once, or wrap with .AsTask()
Empty Update() / FixedUpdate() methodsUnity still calls them (overhead)Remove empty event functions
String-based Invoke("MethodName", t)No compile-time safety, breaks on renameUse coroutines or Awaitable instead

Related Skills

  • unity-foundations -- GameObjects, Components, Transforms, Scenes, Prefabs
  • unity-physics -- Rigidbody, Colliders, Raycasting, Physics materials
  • unity-input -- Input System, InputActions, PlayerInput component

Additional Resources

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Unity Scripting AI 技能有什么作用?

Unity 6 C# scripting guide. Use when writing MonoBehaviour scripts, handling lifecycle events (Awake, Start, Update, FixedUpdate), using coroutines or async/await (Awaitable), working with ScriptableObjects, events, delegates, or core APIs like Vector3, Quaternion, Time, Debug. Based on Unity 6.3 LTS documentation.

为什么在 TypingMind 中使用 Unity Scripting?

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

如何在 TypingMind 中安装 Unity Scripting?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/Nice-Wolf-Studio/unity-claude-skills/tree/main/skills/unity-scripting。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Unity Scripting?

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

Unity Scripting 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以搭配 Unity Scripting 使用,包括 GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等,都可在 TypingMind 中使用您自己的 API 密钥接入。

Unity Scripting AI 技能免费吗?

是的。该技能源自 Nice-Wolf-Studio 在 GitHub 上以 MIT 许可证发布的项目。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

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

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

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

查看全部

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

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