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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM