【发布时间】:2018-04-22 22:46:58
【问题描述】:
代码
Army.Add(new PigSquad("The Old Guard", 10, 4));
其中Army 是List<Unit>,Pigsquad 定义为
public class PigSquad : Unit
{
public override bool Dead { get; set; }
public override string Name { get; set;}
public override int Strength { get; set; }
public override int Age { get { return Age; } set { Age = value; Strength += 20 - Age; if (Age > 20) { Dead = true; } } }
public override int Veterancy { get; set; }
public PigSquad()
{
}
public PigSquad(string Name)
{
this.Name = Name;
}
public PigSquad(string Name, int Strength)
{
this.Name = Name;
this.Strength = Strength;
}
public PigSquad(string Name, int Strength, int Age)
{
this.Name = Name;
this.Strength = Strength;
this.Age = Age;
}
}
运行时使 Unity 编辑器崩溃。我不知道为什么会这样。对此的任何帮助将不胜感激。
【问题讨论】:
-
Unit 类是什么样的?它是从 MonoBehavior 派生的吗?添加到列表的位置在哪里?
-
Age属性的 setter 和 getter 导致无限递归,本质上锁定了试图设置/获取此属性的线程(或整个程序)。将支持字段(例如,称为private int _age;)与Age属性结合使用。 -
谢谢!!!我花了好几个小时试图解决这个问题。
-
仅供参考:由于脑子放屁,对我之前的评论进行了小修正:虽然无限递归会锁定线程设置/获取 Age 属性,但它最终会(实际上相当快)导致一个 StackOverflowException。
-
当我让它运行时,我也遇到了堆栈溢出异常,这可以解释它。