張佑任
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # C# code style in Unity ## 主要守則: * 遵循一致的命名約定 * 統一格式維持程式碼易讀性 * 保持Class和func小且易讀 * 較難理解的程式碼添加註解 ## 命名約定 * 命名不使用 "特殊符號"、"中文"等,即使C#允許使用也需要避免,確保在Unity內和不同平台時不會出現相容性等的問題。 ### 欄位(Fields)和變數(Variables) * 使用名詞作為變數名稱。 * 對於Boolean使用is、has開頭,可以更明確的描述其含意。 * 變數名稱必須清楚明確描述它代表的事物或狀態。 * 盡量避寫縮寫,除非已經約定好了如rigidBody為rb。 * 單字母只用於迴圈變數或數學算式中。 * public變數使用大駝峰(upper camel case)。 * private變數使用小駝峰(lower camel case)。 Example Code: ``` public float DamageMultiplier = 1.5f; public float MaxHealth; public bool IsInvincible; private bool isDead; private float currentHealth; // parameters public void InflictDamage(float damage, bool isSpecialDamage) { // local variable int totalDamage = damage; // local variable versus public member variable if (isSpecialDamage) { totalDamage *= DamageMultiplier; } // local variable versus private member variable if (totalDamage > currentHealth) { /// ... } } ``` * 避免冗余名稱:如果類名為 Player,則無需創建名為 playerScore 或 playerTarget 的成員變數。將它們修剪為"score"或“target”。 * 盡量避免使用var,可以用在區域變數或類型明顯時。 Example Code: ``` var powerUps = new List<PowerUps>(); ``` ### Enum * Enum命名及其Value統一使用大駝峰(upper camel case)。 Example Code: ``` public enum WeaponType { Knife, Gun, RocketLauncher, BFG } ``` ### 類別(Class)和介面(interface) * 命名統一使用大駝峰(upper camel case)。 * interface命名在前方加上"I"。 Example Code: ``` public class ExampleClass : MonoBehaviour { /// ... } public interface IKillable { /// ... } public interface IDamageable<T> { /// ... } ``` ### 函數(Function)和方法(Methods) * 命名統一使用大駝峰(upper camel case)。 * 命名統一以動詞開頭 * 如果Methods為Boolean使用Is、Has開頭。 Example Code: ``` // EXAMPLE: Methods start with a verb public void SetInitialPosition(float x, float y, float z) { /// ... } // EXAMPLE: Methods ask a question when they return bool public bool IsNewPosition(Vector3 currentPosition) { return false; } ``` ### 事件(Events)和事件處理程序(event handlers) * 使用動詞命名事件,並使用現在分詞表示之前(ex:OnOpeningDoor),過去分詞表示之後(ex: OnDoorOpened)。 * 事件委託統一使用System.Action。 * 事件的方法命名使用"On"開頭 * 訂閱事件的方法使用事件名稱去掉On加上"_"加上區別(ex:OpeningDoor_RoomDoor) * 只在必要時使用CustomEventArgs,如有統一的資料結構要發送。 Example Code: ``` // using System.Action delegate public event Action OnOpeningDoor; // event before public event Action OnDoorOpened; // event after public event Action<int> OnPointsScored; public event Action<CustomEventArgs> OnThingHappened public void Send() { OnDoorOpened?.Invoke(); OnPointsScored?.Invoke(points); } private void OnDoorOpened_RoomDoor() { //... } public struct CustomEventArgs { public int ObjectID { get; } public Color Color { get; } public CustomEventArgs(int objectId, Color color) { this.ObjectID = objectId; this.Color = color; } } ``` ### 命名空間(Namespaces) * 命名統一使用大駝峰(upper camel case)。 * 統一在scrite頂端添加using。 * 子命名空間使用"."來分隔。 Example Code: ``` using NamespaceA; using NamespaceA.NamespaceB; namespace NamespaceA { //... } namespace NamespaceA.NamespaceB { //... } ``` ### 格式 > 屬性(Properties) * 對於唯讀屬性使用表達式,並寫在同一行內。 * 單純公開變數不指定屬性,就不需添加,直接讓其Auto-Implemented。 * 其他情況統一使用 { get; set; } 語法 Example Code: ``` public class PlayerData { // the private backing field private int maxHealth; // read-only, returns backing field public int MaxHealth => maxHealth; //Auto-Implemented public int Id; // explicitly implementing getter and setter private string name; public string Name { get => name; set => name = value; } // write-only (not using backing field) public int Power { private get; set; } } ``` > 序列化(Serialization) * 如果要讓private變數在Editor中可見使用[SerializeField]屬性,並添加在同一行。 * 需要限制最大最小值時可以使用[Range(min, max)]屬性。 * 如果參數有複雜結構可以定義一個Class或struct並使用[Serializable]屬性,使其在Editor可見且整齊。 Example Code: ``` using System; using UnityEngine; public class Player : MonoBehaviour { [Serializable] public struct PlayerStats { public int MovementSpeed; public int HitPoints; public bool HasHealthPotion; } // EXAMPLE: The private field is visible in the Inspector [SerializeField] private PlayerStats stats; } ``` > 大括弧、縮排樣式 * 大括弧統一自己佔一行(BSD style)。 * 縮排統一為4個半型空格。 * 不省略大括弧,即使括弧內只有一行。 Example Code: ``` for (int i = 0; i < 100; i++) { DoSomething(i); } for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { ExampleAction(); } } if(true) { ExampleAction(); } ``` ### Class規範 * 由頂部至底部遵循以下層次結構 1. [inject] DI框架注入,頂至底部為Model>System>Manager>其他 2. Fields and Variables 3. Events / Delegates 4. Monobehaviour Methods (Awake, Start, OnEnable, OnDisable, OnDestroy, etc.) 5. Public Methods 6. Private Methods 7. 訂閱事件的方法 或 用於callback的方法 * 其中可以相同功能的為一個group,但如果行數較多建議分開腳本 * 相同層次結構的Method將較高級別的Method放在頂端,如ThrowBall()引用SetInitialVelocity()則將ThrowBall()放在頂端。 ### Method規範 * 方法只實現一個操作或回答一個問題,且名稱要可以明顯的看出其用途。 * 減少使用的參數,避免方法過於複雜。 * 避免過度重載(overloading),如果有需要確保每個方法有不同數量的參數,以防混淆。 * 方法功能需和其描述的用途相同,避免做超出職責的事。 * 與其在方法裡用判斷區分執行的程式,不如分為兩個方法。 Example Code: ``` //Don't do that private float GetAngle(bool isInDegrees) { if(isInDegrees) return ... else return ... } //Do that private float GetAngleInDegrees() { return ... } private float GetAngleInRadians() { return ... } ``` * 避免寫重複的方法。 Example Code: ``` //Don't do that private void PlayExplosionA(Vector3 hitPosition) { explosionA.transform.position = hitPosition; explosionA.Stop(); explosionA.Play(); AudioSource.PlayClipAtPoint(soundA, hitPosition); } private void PlayExplosionB(Vector3 hitPosition) { explosionB.transform.position = hitPosition; explosionB.Stop(); explosionB.Play(); AudioSource.PlayClipAtPoint(soundB, hitPosition); } //Do that private void PlayFXWithSound(ParticleSystem particle, AudioClip clip, Vector3 hitPosition) { particle.transform.position = hitPosition; particle.Stop(); particle.Play(); AudioSource.PlayClipAtPoint(clip, hitPosition); } ``` ### 註解 * 不要新增註解來取代錯誤代碼 * 正確命名的類、變數或方法代替註釋 * 盡可能將注釋放在單獨的行上,而不是放在一行代碼的末尾 * 在大多數情況下使用雙斜杠"//"" * 對序列化欄位使用工具提示而不是註釋 * 在公共Method前面使用摘要 XML 標記(summary) * 雙斜杠後添加一個半形空格 * 刪除註釋的程式碼,如果有需要回復程式碼多用版控或寫成控制項。 * 添加 "TODO:" 在需要實現的程式碼上,且完成時記得刪除。 * 添加 "UNDONE:" 在未完成、做一半的程式碼上。 * 添加 "FIXME:" 在有問題、需要修正的程式碼上。 Example Code: ``` [Tooltip(“The amount of side-to-side friction.”)] public float Grip; /// <summary> /// Fire the weapon /// </summary> public void Fire() { ... } ``` ### 參考 * youtube: [Tips for creating your own C# code style guide | Tutorial](https://www.youtube.com/watch?v=bKGMkkf4X0o) * youtube: [Coding Conventions in Unity](https://www.youtube.com/watch?v=OD0EJb7l068) * 網路文章: [第八屆 CMoney 軟體訓練營 - 共筆筆記]( https://hackmd.io/@lee0709/r1FyjN5zO/https%3A%2F%2Fhackmd.io%2FnCNMe61tQJaQnNOcxGFecA)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully