如何在未被占用的随机Vector3位置生成对象?

问题描述 投票:0回答:1

我正在尝试在游戏板上的空闲位置随机生成游戏对象。

我计划采取的步骤是:

  1. 创建一个包含所有可用位置坐标的 Vector3 数组
  2. 使用 Instantiate(对象原始,Vector3 位置,四元数旋转),在数组的索引上调用 Random.Range 来随机生成
  3. 创建一个布尔值来检查索引处的位置是否仍然可用
    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. 错误的数组声明符:要声明托管数组,等级说明符位于变量标识符之前。要声明固定大小的缓冲区字段,请在字段类型之前使用固定关键字。

  2. 无法在变量声明中指定数组大小(尝试使用“新”表达式进行初始化)

如何解决?

为了修复错误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# unity-game-engine initialization
1个回答
0
投票

这是基本语法错误。在 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);
© www.soinside.com 2019 - 2024. All rights reserved.