Unity 关于属性的get/set

学习Unity的可能多数是C#转过来的, 一进来的时候你会发现Unity编写代码,在一些视频或文章中.基本都没有用过get/set使用, 多数是public string name;这样写的公开字段,可能在设计的时候
视图上设置字段无法与get/set联动起来(只是一种猜测)
   
[SerializeField]可以让字段显示在Inspector上面.private字段也可以.
   
在Inspector中设置属性,并没有执行set方法

[SerializeField]
    private string name;
    public string Name
    {
        get { return name; }
        set 
        {
            Debug.Log("通过属性设置");
            name = value;
        }
    }

如果你需要在编辑器设置属性,相应set方法需要以下做法

创建TestInspector.cs放在Editor目录下

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;

[CustomEditor(typeof(Test))]
public class TestInspector : Editor
{
    Test model;
    public override void OnInspectorGUI() 
    {
        model = target as Test;
        string name = EditorGUILayout.TextField("名字",model.name);
        if (model.Name != name)
        {
            model.Name = name;
        }

        base.DrawDefaultInspector();
    }

}

Test实体类:

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {

    //[SerializeField]
    private string name;

    public string Name
    {
        get 
        {
            Debug.Log("通过属性get设置");
            return name;
        }
        set 
        {
            Debug.Log("通过属性set设置");
            name = value;
        }
    }


}

 

image

原文地址: 雨凇MOMO研究学院http://www.xuanyusong.com/archives/3406

posted @ 2015-02-08 15:23  盘子脸  阅读(4324)  评论(0编辑  收藏  举报