我正在尝试在游戏板上的空闲位置随机生成游戏对象。
我计划采取的步骤是:
Vector3[] randomPos = new Vector3[9];
Vector3 randomPos[0] = new Vector3(-2.5, 3.6, 0);
Vector3 randomPos[1] = new Vector3(0, 3.6, 0);
Vector3 randomPos[2] = new Vector3(2.5, 3.6, 0);
Vector3 randomPos[3] = new Vector3(-2.5, 1, 0);
Vector3 randomPos[4] = new Vector3(0, 1, 0);
Vector3 randomPos[5] = new Vector3(2.5, 1, 0);
Vector3 randomPos[6] = new Vector3(-2.5, -1.6, 0);
Vector3 randomPos[7] = new Vector3(0, -1.6, 0);
Vector3 randomPos[8] = new Vector3(2.5, -1.6, 0);
我在步骤 1 中的代码导致以下错误:
错误的数组声明符:要声明托管数组,等级说明符位于变量标识符之前。要声明固定大小的缓冲区字段,请在字段类型之前使用固定关键字。
无法在变量声明中指定数组大小(尝试使用“新”表达式进行初始化)
如何解决?
为了修复错误1,我尝试了
Vector3[0] randomPos = new Vector3(-2.5, 3.6, 0);
Vector3[1] randomPos = new Vector3(0, 3.6, 0);
Vector3[2] randomPos = new Vector3(2.5, 3.6, 0);
Vector3[3] randomPos = new Vector3(-2.5, 1, 0);
Vector3[4] randomPos = new Vector3(0, 1, 0);
Vector3[5] randomPos = new Vector3(2.5, 1, 0);
Vector3[6] randomPos = new Vector3(-2.5, -1.6, 0);
Vector3[7] randomPos = new Vector3(0, -1.6, 0);
Vector3[8] randomPos = new Vector3(2.5, -1.6, 0);
基于 https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/array-declaration-errors#invalid-array-rank 的建议。 错误 1 更改为“GameScript”类型已包含“randomPos”的定义... 对于错误2,我不明白这个问题,因为我已经使用了new关键字?非常感谢你
这是基本语法错误。在 C# 中,声明并初始化数组时,在为各个元素赋值时不再使用数组索引语法(randomPos[0]、randomPos[1] 等)。固定代码:
Vector3[] randomPos = new Vector3[9];
randomPos[0] = new Vector3(-2.5, 3.6, 0);
randomPos[1] = new Vector3(0, 3.6, 0);
randomPos[2] = new Vector3(2.5, 3.6, 0);
randomPos[3] = new Vector3(-2.5, 1, 0);
randomPos[4] = new Vector3(0, 1, 0);
randomPos[5] = new Vector3(2.5, 1, 0);
randomPos[6] = new Vector3(-2.5, -1.6, 0);
randomPos[7] = new Vector3(0, -1.6, 0);
randomPos[8] = new Vector3(2.5, -1.6, 0);