C#遇到属性变量问题(获取和设置)

时间:2017-02-20 07:41:29

标签: c# variables unity3d properties

我在理解属性如何在C#中工作时遇到了一些麻烦。首先是快速的背景:我在团队中处理一个级别管理器,其目的是包含每个级别的游戏级别和信息列表(级别描述,级别图像等),所有这些都保存在单个ScriptableObject中。

所以假设我有3个属性,sceneIndex,sceneName和LevelID。

sceneIndex 是一个变量,我应该能够在Unity的检查器中进行更改,并且应该与构建设置中的级别索引匹配。

sceneName 不应该在unity的检查器中编辑,并且应该始终是关卡的名称。 (这由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
}

谢谢〜斯科特

1 个答案:

答案 0 :(得分:1)

您似乎误解了属性的工作方式。您使用set{ sceneName = SceneManager.GetSceneAt (sceneIndex).name; }就好像它会描述它的工作方式(某种基于属性的开发)。

属性用于封装字段。因此,他们提供了一种&#34; get&#34;和&#34;设置&#34;特征。只有在使用MyProperty = value时才会调用set功能;并且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(现在可能无用)来访问此数据。

编辑:使用setter:

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