代码命名

Public变量

所有公开的变量请勿使用简写,如请尽量不要使用pos,而是使用position,私有变量无所谓。

字段(Field)

驼峰命名

public class DemoUI : MonoBehaviour {
    [LabelText("一些整数")]
    [MinValue(0), MaxValue(10)]
    public int someIntegers = 2;
    
    [LabelText("标签")]
    [Required, SceneObjectsOnly]
    public TextMeshProUGUI label;
}

属性(Property)

帕斯卡命名

public class DemoUI : MonoBehaviour {
    [SerializeField] //序列化,让其显示在Unity Editor里
    private int _health = 4;
    
    [SerializeField] //序列化,让其显示在Unity Editor里
    private int _maxHealth = 100;

    public int Health //外部需要使用HP值应该调用的接口
    {
        get => _health.Clamp(0, _maxHealth); //在获取该值时,限制在0和最大HP值之间
        set => _health = value.Clamp(0, _maxHealth); //设置HP也是,限制_HP在0到最大HP值之间
    }
}

特性(Attribute)

与通常的类不同,里面的字段或属性请用帕斯卡命名。

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
[Conditional("UNITY_EDITOR")]
public class ListItemSelectorAttribute : Attribute
{
    public string OnSelectMethod;
    public Color ColorOnSelect => new(R, G, B, A);
    public float R, G, B, A;

    public ListItemSelectorAttribute(string OnSelectMethod, float R = 0.3f, float G = 0.5f, float B = 1f, float A = 0.5f)
    {
        this.OnSelectMethod = OnSelectMethod;
        this.R = R; 
        this.G = G;
        this.B = B;
        this.A = A;
    }
}

函数(Function)

帕斯卡命名法(Pascal Case)

public class DemoUI : MonoBehaviour {
    [Button(ButtonSizes.Large)] //显示一个大号按钮
    public void DisplayJJC()
    {
        Debug.Log("JJC");
    }
}

常值(Constant)

全大写+下划线命名

public class DemoUI : MonoBehaviour {
    //根号2的值
    public const double SQRT2 = 1.41421356237309504880168872420969807856967187537694807317667973799;
    
    //JJC的名字
    public const string JJC_NAME = "Jiacheng Jiang";
}

类(Class)

帕斯卡命名。

结构(Struct)

帕斯卡命名。

模板(Template)

模板的类型请以 T 开头,如下面的 TPrefabTInstance

public class SimpleGameItemBundle<TPrefab, TInstance> : GamePrefabCoreBundle<TPrefab>
    where TPrefab : SimpleGameItemBundle<TPrefab, TInstance>.GameItemPrefab, new()
    where TInstance : SimpleGameItemBundle<TPrefab, TInstance>.GameItem, new()

接口(Interface)

全部以 I 开头命名,如IEnumerable<T>。

枚举(Enumeration)

全部帕斯卡命名法

[Flags]
public enum FaceType
{
    [LabelText("右(1, 0, 0)")]
    Right = 1 << 1,
    [LabelText("左(-1, 0, 0)")]
    Left = 1 << 2,
    [LabelText("上(0, 1, 0)")]
    Up = 1 << 3,
    [LabelText("下(0, -1, 0)")]
    Down = 1 << 4,
    [LabelText("前(0, 0, 1)")]
    Forward = 1 << 5,
    [LabelText("后(0, 0, -1)")]
    Back = 1 << 6,
    [LabelText("所有朝向")]
    All = Right | Left | Up | Down | Forward | Back,
}

事件(Event)

帕斯卡命名

public event Action<int, int> OnValueChanged;

元组(Tuple)

请带上内部每个类型的命名,而不是只有类型,如下面的(int slotIndex, Item item),而不是(int, Item)

public IEnumerable<(int slotIndex, Item item)> GetAllItems()
{
	return items.Select((t, index) => (index, t));
}

委托(Delegate)

帕斯卡命名

如果委托的参数比较多,请勿用Action<>,请用delegate语法并给每个参数标上名字。

最后更新于

这有帮助吗?