【问题标题】:Unity C# Constructor is not called properly未正确调用 Unity C# 构造函数
【发布时间】:2018-02-11 16:56:19
【问题描述】:

当在编辑模式下从 Unity 检查器创建新的 List 元素时,我在从其构造函数初始化字符串时遇到了一些问题。

它所做的只是将“调用测试”写入控制台,而不是将其名称和描述初始化为占位符文本。

public class StatsManager : MonoBehaviour {   
    [System.Serializable]
    public class StatValue {
        public string name;
        public string description;
        public int currentValue;

        public StatValue(){
            this.name = "Times hit";
            this.description = "This is how much you have been hit since the start of the game.";
            Debug.Log("Call test");
        }
    }

    [SerializeField]
    public List<StatsManager.StatValue> stats;
}

【问题讨论】:

  • 我看不到对该构造函数的任何调用...
  • 当我在控制台中收到 debug.log 消息时,构造函数被调用。它会在实例化时自动调用。
  • 不确定我是否理解。所以有一些隐藏代码,其中 stats = new List() 和 stats.Add(new StatsManager.StatValue()),对吧?
  • @McMidas:您向我们展示了一些代码。您没有向我们展示您使用上述代码的地方,那么我们应该如何帮助您调试正在发生的事情?
  • 哦忘了说我在unity的inspector中编辑了列表

标签: c# list class unity3d initialization


【解决方案1】:

好的,我找到了一个解决方案,以防有人遇到同样的问题。不需要 cTor 或 ISerializableCallbackReceiver。这使用了也会在实例化时调用的 Reset Callback(来自 coq)。干杯!

 [System.Serializeable]
 public class Test {
     int value = 500;
 }
 public class TestManager : MonoBehaviour {
     public Test testInt;
     public List<Test> testInts;
     void Reset(){
         testInts = new List<Test>(){
             new Test()
         };
     }
 }

来自https://answers.unity.com/questions/1467289/default-value-on-list-vanished.html?childToView=1467368#comment-1467368

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 2014-10-25
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 2021-09-27
    相关资源
    最近更新 更多