英文:
Getter/Setter make Unity 2020.2.20 crashes
问题
我有2个脚本如下:
config.cs
public enum CONTROL_TYPE : int
{
TOUCH_CONTROL = 0,
TILT_CONTROL = 1,
};
public CONTROL_TYPE controlType
{
get { return controlType; }
set { controlType = value; }
}
menu.cs
config gameConfig
void Start()
{
gameConfig.controlType = GameConfig.CONTROL_TYPE.TOUCH_CONTROL;
}
我正在尝试设置controlType
,但是当这发生时Unity编辑器总是崩溃。有人可以帮忙指出我哪里出错了吗?
英文:
I have 2 scripts as follow:
config.cs
public enum CONTROL_TYPE : int
{
TOUCH_CONTROL = 0,
TILT_CONTROL = 1,
};
public CONTROL_TYPE controlType
{
get { return controlType; }
set { controlType = value; }
}
menu.cs
config gameConfig
void Start()
{
gameConfig.controlType = GameConfig.CONTROL_TYPE.TOUCH_CONTROL;
}
I am trying to set the controlType
, but the Unity editor always crashes when it happen.
Can anyone help to point where I get this wrong?
答案1
得分: 1
问题在于您的属性 getter 和 setter 是自引用的。这将导致无限递归。
您可以以两种方式解决它:
-
添加一个显式数据成员,用于保存属性值:
private CONTROL_TYPE controlType; // 这是新的数据成员 public CONTROL_TYPE ControlType { get { return controlType; } set { controlType = value; } }
-
让编译器在幕后为您生成它,使用这种更简洁的语法(与第一种选项等效):
public CONTROL_TYPE ControlType { get; set; }
在您的情况下,我更喜欢更优雅的第二个选项。
英文:
The problem is that your property getter and setter are self referencing.
This will cause an infinite recursion.
You can solve it in 2 ways:
-
Add an explicit data member that will hold the property value:
private CONTROL_TYPE controlType; // this is the new data member public CONTROL_TYPE ControlType { get { return controlType; } set { controlType = value; } }
-
Let the compiler generate it for you behind the scene, by using this more succinct syntax (equivalent to the 1st option):
public CONTROL_TYPE ControlType { get; set; }
In your case, I would prefer the more elegant 2nd option.
答案2
得分: -1
原来是个愚蠢的错误。我忘了为属性创建变量,而是尝试直接填充属性本身。
应该像这样:
config.cs
public enum CONTROL_TYPE : int
{
TOUCH_CONTROL = 0,
TILT_CONTROL = 1,
};
private CONTROL_TYPE _controlType; // 在这里
public CONTROL_TYPE ControlType
{
get { return _controlType; }
set { _controlType = value; }
}
menu.cs
...
....
config gameConfig
void Start()
{
gameConfig.ControlType = GameConfig.CONTROL_TYPE.TOUCH_CONTROL;
}
...
....
英文:
Turns out it's a silly mistake. I forgot to make variable for the properties and instead trying to fill the properties itself.
It should be like this:
config.cs
public enum CONTROL_TYPE : int
{
TOUCH_CONTROL = 0,
TILT_CONTROL = 1,
};
private CONTROL_TYPE _controlType; // This one here
public CONTROL_TYPE ControlType
{
get { return _controlType; }
set { _controlType = value; }
}
menu.cs
...
....
config gameConfig
void Start()
{
gameConfig.ControlType = GameConfig.CONTROL_TYPE.TOUCH_CONTROL;
}
...
....
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论