【问题标题】:Why does Unity give an error when adding an object to a list using new()? [closed]为什么 Unity 在使用 new() 将对象添加到列表时会出错? [关闭]
【发布时间】:2021-10-06 04:09:19
【问题描述】:

我在 Unity 中有以下代码

public class Objects : MonoBehaviour
{
List<GridObject> Grid = new List<GridObject>();
    // Start is called before the first frame update
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
       Grid.Add( new (GridObject) {xCord = 0, zCord = 0, ObjectID = 0}); 
    }
}

它给出了错误:“元组必须包含至少两个元素”在 GameObject 我认为它与 new() 函数有关,但我不知道如何

【问题讨论】:

  • 为什么GridObject 用括号括起来?是错字吗?
  • 您的意思是new GridObject() 吗?
  • @derHugo 是的,那是正确的
  • @gunr2171 不,这不仅仅是一个错字,我认为这是正确的

标签: c# unity3d arraylist new-operator


【解决方案1】:

虽然新函数有时被列为“new()”,但使用它的正确格式实际上是 new [object type]()

例如


    var someObject = new object();

所以在你的情况下你会想要


    public class Objects : MonoBehaviour
    {
    List<GridObject> Grid = new List<GridObject>();
        // Start is called before the first frame update
        void Start()
        {
        }
    
        // Update is called once per frame
        void Update()
        {
           Grid.Add( new GridObject() {xCord = 0, zCord = 0, ObjectID = 0}); 
        }
    }

另外,如果您想隔离错误,您可以先创建新的 GridObject,然后将其添加到列表中

var gridObject = new GridObject {xCord = 0, zCord = 0, ObjectID = 0};
Grid.Add(gridObject); 

有点不相关,但您是否打算在每一帧的网格中添加一个新的 GridObject,因为这就是这段代码目前要做的事情?

Microsoft documentation on new

【讨论】:

  • "有点不相关,但您是否打算在每一帧的网格中添加一个新的 GridObject,因为这就是这段代码当前要做的事情?"不,那只是暂时的,因为我想在使用系统之前先制作系统
  • 我会说这不是一个错字,更多的是对如何使用 new() 的误解(并且在评论中得到了 OP 的确认),我对此进行了解释并提供了文档。不确定是否值得投反对票...
  • @derHugo 我们不应该回答问题是发布者不了解如何使用函数的问题吗? ;)
  • 这是一个非常直接的错字.. 或者至少我会声称这是基本的c# 语法,它不会帮助任何未来的读者;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 2023-01-29
  • 1970-01-01
  • 2013-03-25
  • 1970-01-01
  • 2022-11-14
相关资源
最近更新 更多