为什么在使用 new() 将对象添加到列表时 Unity 会报错?

Why does Unity give an error when adding an object to a list using new()?

我在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() 函数有关,但我不知道如何

虽然新函数有时被列为“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