在 Unity C# 中创建数组

本文关键字:创建 数组 Unity | 更新日期: 2023-09-27 18:35:15

我是美术师,我想创建一个游戏。我在 JS 中有一个代码,当我转换为 C# 时,这段代码不起作用。请帮助我。这是代码:

#pragma strict
var numberOfTiles = 8;
var tileObjects : GameObject[];
var tileLocations = new Array
(
    Vector3 (-4.44,3.2,0), Vector3 (-2.7,3.2,0), Vector3 (-0.9,3.2,0), Vector3 (0.95,3.2,0),    Vector3 (2.76,3.2,0), Vector3 (4.56,3.2,0), Vector3 (6.3,3.2,0),
    Vector3 (-4.44,1.3,0), Vector3 (-2.7,1.3,0), Vector3 (-0.9,1.3,0), Vector3 (0.95,1.3,0), Vector3 (2.76,1.3,0), Vector3 (4.56,1.3,0), Vector3 (6.3,1.3,0),
    Vector3 (-4.44,-0.4,0), Vector3 (-2.7,-0.4,0), Vector3 (-0.9,-0.4,0), Vector3 (0.95,-0.4,0), Vector3 (2.76,-0.4,0), Vector3 (4.56,-0.4,0), Vector3 (6.3,-0.4,0),
    Vector3 (-4.44,-2.4,0), Vector3 (-2.7,-2.4,0), Vector3 (-0.9,-2.4,0), Vector3 (0.95,-2.4,0), Vector3 (2.76,-2.4,0), Vector3 (4.56,-2.4,0), Vector3 (6.3,-2.4,0),
    Vector3 (-4.44,-4,0), Vector3 (-2.7,-4,0), Vector3 (-0.9,-4,0), Vector3 (0.95,-4,0), Vector3 (2.76,-4,0), Vector3 (4.56,-4,0), Vector3 (6.3,-4,0)
);

在 Unity C# 中创建数组

试试这个格式:

var tileLocations = new Vector3[] {         
    new Vector3 (-4.44,3.2,0), 
    new Vector3 (-2.7,3.2,0), 
     ... 
} 

"[]"使它成为一个数组,在本例中为 Vector3 类型。

正确的语法是

int numberOfTiles = 8;    // <- var is superfluous here, put it like int
GameObject[] tileObjects; // <- Seems that you want to declare GameObject[]
var tileLocations = new Vector3[] // <- Vector3[], not Array
(
    Vector3 (-4.44,3.2,0), Vector3 (-2.7,3.2,0), Vector3 (-0.9,3.2,0), Vector3 (0.95,3.2,0),    Vector3 (2.76,3.2,0), Vector3 (4.56,3.2,0), Vector3 (6.3,3.2,0),
    Vector3 (-4.44,1.3,0), Vector3 (-2.7,1.3,0), Vector3 (-0.9,1.3,0), Vector3 (0.95,1.3,0), Vector3 (2.76,1.3,0), Vector3 (4.56,1.3,0), Vector3 (6.3,1.3,0),
    Vector3 (-4.44,-0.4,0), Vector3 (-2.7,-0.4,0), Vector3 (-0.9,-0.4,0), Vector3 (0.95,-0.4,0), Vector3 (2.76,-0.4,0), Vector3 (4.56,-0.4,0), Vector3 (6.3,-0.4,0),
    Vector3 (-4.44,-2.4,0), Vector3 (-2.7,-2.4,0), Vector3 (-0.9,-2.4,0), Vector3 (0.95,-2.4,0), Vector3 (2.76,-2.4,0), Vector3 (4.56,-2.4,0), Vector3 (6.3,-2.4,0),
    Vector3 (-4.44,-4,0), Vector3 (-2.7,-4,0), Vector3 (-0.9,-4,0), Vector3 (0.95,-4,0), Vector3 (2.76,-4,0), Vector3 (4.56,-4,0), Vector3 (6.3,-4,0)
);

您实际上不想要的代码的另一个问题

  int numberOfTiles = 8; 

因为只要你需要,你可以打电话

  tileLocations.Length; // <- Length of the array i.e. number of tiles