【问题标题】:How to add a new object to a list without a variable?如何在没有变量的情况下将新对象添加到列表中?
【发布时间】:2016-05-14 18:53:23
【问题描述】:

我试图通过构造一个新的 asd 然后添加它来将我的 asd 类的新实例添加到列表中,但 Unity 给出了一个未设置为对象实例的对象错误。

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class asd {
    public int a = 0;
    public string s = "asd";

    public asd (int apop, string ssdf) {
        a = apop;
        s = ssdf;
    }
}

public class test : MonoBehaviour {

    public List<asd> list;

    // Use this for initialization
    void Start () {
        list.Add (new asd(1, "yeee"));
        list.Add (new asd(456, "oooo"));
    }

    // Update is called once per frame
    void Update () {

    }
}

【问题讨论】:

  • @MXD 这看起来像是一个快速代码示例,因为名称是 test
  • @MXD 你的评论不具建设性和粗鲁。
  • 是的,这是一个测试,这就是为什么名字都很糟糕
  • 您应该单击编辑并将其更改为经过仔细考虑的示例名称。

标签: c# list unity3d


【解决方案1】:

如下正确实例化您的列表,然后将asd 添加到其中

public List<asd> list = new List<asd>();

// Use this for initialization
void Start () {
      list.Add(new asd(1, "yeee"));
      list.Add(new asd(456, "oooo"));
    }

【讨论】:

    【解决方案2】:
    public List<asd> list;
    

    这说明list 是什么,它没有实例化它:

    public List<asd> list = new List<asd>();
    

    请注意,类名应以大写字母 (PascalCase) 开头。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-08
      • 2012-04-27
      • 2022-12-18
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多