实现设计师友好的代码
|Word count:452|Reading time:2min|Post View:
设计师友好的代码
为什么要开发设计师友好的代码?
好处有很多,可以防止一些意想不到的bug,也可以提高沟通效率……
设置参数反射标记
- 通过Serializable可以提高参数的可读性,如下图的MoveSettings和AttackSettings。
- 通过[Min(0f)],[HideInInspector],……,防止设计师乱搞。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| namespace Character { [Serializable] public class MoveSettings { [Min(0f)] public float moveSpeed; }
[Serializable] public class AttackSettings { public GameObject weaponPrefab; public Transform weaponEquippedTransform;
[HideInInspector] public BasicWeapon2D weapon2DComponent; [HideInInspector] public Color color;
[Min(0f)] public float collisionDamage; }
|
添加上下文
通过[ContextMenu(“”)],可以为脚本添加上下文,如下。

1 2 3 4 5 6 7 8 9 10 11
| public abstract class BasicCharacterController : MonoBehaviour { [ContextMenu("Init")] public void Init() { moveSettings.moveSpeed = 3f;
attackSettings.collisionDamage = 0f; } } }
|
在编辑器中运行脚本
通过[ExecuteInEditMode]可以在编辑器中通过脚本调整数据,用在UI里真的太香了,不用像上一篇那样拷贝复制了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| namespace UI { [ExecuteInEditMode] public class PageLayoutAdjuster : MonoBehaviour { private void Awake() { #if DEBUG if (transform.childCount != 3) Debug.LogError("PageLayout requires exactly 3 child objects: Header, Content, and Footer.");
_headerRectTransform = gameObject.transform.GetChild(0).gameObject.GetComponent<RectTransform>(); _contentRectTransform = gameObject.transform.GetChild(1).gameObject.GetComponent<RectTransform>(); _footerRectTransform = gameObject.transform.GetChild(2).gameObject.GetComponent<RectTransform>();
headerHeightPercent = 1f - _headerRectTransform.anchorMin.y; footerHeightPercent = _footerRectTransform.anchorMax.y; #endif }
private void Update() { #if DEBUG _headerRectTransform.anchorMin = new Vector2(0f, 1f - headerHeightPercent); _headerRectTransform.anchorMax = new Vector2(1f, 1f);
_contentRectTransform.anchorMin = new Vector2(0f, footerHeightPercent); _contentRectTransform.anchorMax = new Vector2(1f, 1f - headerHeightPercent);
_footerRectTransform.anchorMin = new Vector2(0f, 0f); _footerRectTransform.anchorMax = new Vector2(1f, footerHeightPercent); #endif }
#if DEBUG [Range(0f, 1f)] public float headerHeightPercent; [Range(0f, 1f)] public float footerHeightPercent;
private RectTransform _headerRectTransform; private RectTransform _contentRectTransform; private RectTransform _footerRectTransform; #endif } }
|
实现ReadOnly反射标记
如果你想让设计师可以看到一些参数,但不能调整(调试用),就需要自己来实现ReadOnly这个标记,效果如下。

1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class ReadOnlyAttribute : PropertyAttribute { }
[CustomPropertyDrawer(typeof(ReadOnlyAttribute))] public class ReadOnlyDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { GUI.enabled = false; EditorGUI.PropertyField(position, property, label, true); GUI.enabled = true; } }
|