unity-csharp成员变量变化监听

做编辑器工具是可能会用到的一个技巧,例如修改 monobehavior 某个变量值,重新做下排序、对位置等功能


  • 其实就是利用 monobehavior 里的一个方法 OnValidate ,这里是每次修改都重新排序一下
    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
    45
    46
    47
    48
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    [ExecuteInEditMode]
    public class SortAllBuilding : MonoBehaviour {
    public int row = 7;
    public int xWidth = 3;
    public int zWidth = 3;
    public Vector3 pos = Vector3.zero;
    public bool refresh = false;

    private bool _isDirty = true;

    void Start () {
    _isDirty = true;
    }

    void OnValidate() {
    _isDirty = true;
    }

    void Sort() {
    int xCnt = 0;
    int zCnt = 0;
    int total = transform.childCount;
    Debug.LogFormat("--- 总建筑数量:{0}", total);
    for (int i = 0; i < total; i++) {
    Transform tf = transform.GetChild(i);
    tf.position = new Vector3(xWidth * xCnt, 0f, zWidth * zCnt);

    if (xCnt == row) {
    zCnt += 1;
    xCnt = 0;
    } else {
    xCnt += 1;
    }

    }
    }

    void Update() {
    if (_isDirty) {
    _isDirty = false;
    Sort();
    }
    }
    }