Unity3D-Inspector视图中的get/set使用

我们想要在编辑模式下在Inspector中编辑属性.

public int width{
    get {
        return _width;
    }
    set {
        print ("set:" + value);
        _width = value;
    }
}
[SerializeField]//序列化一个区域,在Inspector视图中显示出来.
private int _width;

这里写图片描述
在编辑模式下用鼠标修改Width的值,发现set压根就没有执行.因为我们修改的是private _width而不是public width.我们需要的是修改后者.
将Test挂在任意游戏对象上.

using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
    public int width {
        get{return _width;}
        set{Debug.Log("set:" + value);_width = value;}
    }
    private int _width;
}

将TestInspector.cs放在Editor目录下

using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
[CustomEditor(typeof(Test))]
public class TestInspector : Editor {
    Test model;
    public override void OnInspectorGUI() {
        model = target as Test;
        int width = EditorGUILayout.IntField("Width", model.width);
        if(model.width != width){
            model.width = width;
        }
        base.DrawDefaultInspector();
    }
}

这里写图片描述
在编辑模式下用鼠标修改width的值,log输出说明get/set已经响应了.
另一种实现方式:这里
ResourceFrom:这里

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值