2017-02-20 60 views
-2

我在理解C#中的屬性如何工作時遇到了一些麻煩。首先介紹一下背景知識:我在統一級別管理器上工作,其目的是包含每個級別的遊戲級別和信息列表(級別描述,級別圖像等),所有這些都保存在一個ScriptableObject中。C#遇到屬性變量問題(獲取並設置)

因此,讓我說我有3個屬性,sceneIndex,sceneName和LevelID。

sceneIndex是一個變量,我應該能夠在unity的檢查器中進行更改,並且應該在構建設置中匹配級別索引。

sceneName不應該在團結督察中編輯,並且應該始終是關卡的名稱。 (這是由sceneIndex確定的)

LevelID應始終設置爲級別列表中此類的索引。

這是我當前的代碼 - 當前當我更改sceneIndex時,我的sceneName未更新爲檢查器中的匹配名稱,並且當我向列表中添加新元素時,LevelID未更新。

public class LevelDataBase : ScriptableObject { 

    [System.Serializable] 
    public class LevelData { 

     [SerializeField] 
     public string p_sceneName{//the levelName 
      get{ return sceneName; } 
      set{ sceneName = SceneManager.GetSceneAt (sceneIndex).name; }// it should always be set depending on the Scene Index 
     } 
     public string sceneName;//Properties dont display in unity's inspector so i have to use secondary variable for it to be displayed. 

     public int sceneIndex;//the scene index i should be able to change and then the scene Name should Updatedepending on the value 


     [SerializeField] 
     public int p_LevelID {//the Level id Should always be the index of this class in the list. 
      get{ return LevelID; } 
      set{ LevelID = LevelList.IndexOf (this); } 
     } 
     public int LevelID; 

     public string DisplayName; 
     public Sprite Image; 
     public string Description; 
    } 

    public List<LevelData> LevelList;//this is a list containing all the levels in the game 
} 

謝謝〜斯科特

+2

「不工作」 - 是不是一個正確的描述。 –

回答

1

看來你是誤會性質的工作方式。您使用set{ sceneName = SceneManager.GetSceneAt (sceneIndex).name; }就好像它會描述它應該工作的方式(某種基於屬性的開發)。

屬性用於封裝字段。因此他們提供了一種「獲取」和「設置」功能。設置的功能只有在使用MyProperty = value時纔會被調用; get屬性將由value = MyProperty觸發。

所以感覺你的套件應該在get中重命名,你應該擺脫你以前的得到。

public string SceneName{//the levelName 
      get{ return SceneManager.GetSceneAt (sceneIndex).name; }// it should always be set depending on the Scene Index 
     } 

然後在你的代碼,你應該總是使用訪問SceneName而非公共字符串sceneName這個數據(也就是現在的可能沒用)。

編輯:使用二傳手:

public int SceneIndex{ 
    set 
    { 
     sceneIndex = value; 
     sceneName= SceneManager.GetSceneAt (sceneIndex).name; }// it should always be set depending on the Scene Index 
    } 
} 
+0

嘿布魯諾感謝他們回覆。是誤解了屬性如何工作,所以感謝解釋。但是我必須使用「公共字符串sceneName」變量的原因是因爲在unity的檢查器中顯示的不正確。這就是爲什麼即時通訊使用第二個變量,並在屬性被改變時改變它。 – WeirderChimp53

+0

我不習慣統一,但對我來說,屬性被忽略似乎很危險。無論如何,你可以做的是使用setter來修改sceneIndex,它也會更新sceneName。我更新了我的答案以反映這一點。 –

+0

所以我搞砸了,並實現了你的代碼片段。現在是工作,如果我在運行時調用「SceneIndex = 1;」 sceneIndex和sceneName被更新。唯一的問題是,因爲im在unity的檢查器中改變sceneIndex(variable not property)屬性值永遠不會被改變,因此不會調用「set」而不會更新sceneName。 – WeirderChimp53