【问题标题】:Constructor That Crashes Unity使 Unity 崩溃的构造函数
【发布时间】:2018-04-22 22:46:58
【问题描述】:

代码

Army.Add(new PigSquad("The Old Guard", 10, 4));

其中ArmyList<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。
  • 当我让它运行时,我也遇到了堆栈溢出异常,这可以解释它。

标签: c# unity3d crash


【解决方案1】:
public override int Age { get { return Age; } set { Age = value; Strength += 20 - Age; if (Age > 20) { Dead = true; } } }

应该是

private int _Age; //maybe make this in your UNIT object as well and that way you do not need it in your child.
public override int Age { get { return _Age; } set { _Age = value; Strength += 20 - _Age; if (Age > 20) { Dead = true; } } }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多