当我尝试以C#统一添加更多内容时,删除其先前内容的数组

时间:2018-08-16 13:22:07

标签: c# arrays unity3d

我最近开始统一学习C#。我仍然不了解很多代码,数组只是其中之一。

我正在尝试编写一个代码,以查找对象,对对象进行计数,然后将它们的位置存储在Vector3数组中。

GameObject[] ExistingObjects = GameObject.FindGameObjectsWithTag("Parts");
float CountObjects = ExistingObjects.Length;

for (int i = 0; i < CountObjects; i++)
{
    float ObjectPositionX = ExistingObjects[i].transform.position.x;
    float ObjectPositionZ = ExistingObjects[i].transform.position.z;
    Vector3[] ObjectPositions = new[] { new Vector3(ObjectPositionX, 0, ObjectPositionZ) };
}

当场景中只有一个对象时,一切正常。当我添加的数量更多时,它将从找到的第一个对象中获取第一个Vector3,然后在将第二个Vector3放入数组时将其删除。因此,我剩下的(无论我在场景中放置了多少个对象)都是ObjectPositions [0]。

正如我已经说过的,我对C#编码还很陌生。

3 个答案:

答案 0 :(得分:4)

您正在循环中创建一个新变量ObjectPositions。您应该在循环外部创建此变量,并仅在循环内部向此变量添加Vector3

这看起来像这样:

Vector3[] ObjectPositions = new Vector3[CountObjects];
for (int i = 0; i < CountObjects; i++)
{
    float ObjectPositionX = ExistingObjects[i].transform.position.x;
    float ObjectPositionZ = ExistingObjects[i].transform.position.z;
    ObjectPositions[i] = new Vector3(ObjectPositionX, 0, ObjectPositionZ);
}

答案 1 :(得分:1)

改用泛型

GameObject[] ExistingObjects = GameObject.FindGameObjectsWithTag("Parts");
float CountObjects = ExistingObjects.Length;
List<ObjectPositions> Vector3 = new List<ObjectPositions>();
for (int i = 0; i < CountObjects; i++)
{
    float ObjectPositionX = ExistingObjects[i].transform.position.x;
    float ObjectPositionZ = ExistingObjects[i].transform.position.z;
    Vector3.Add(new Vector3(ObjectPositionX, 0, ObjectPositionZ));
}

答案 2 :(得分:0)

尝试一下:

GameObject[] ExistingObjects = GameObject.FindGameObjectsWithTag("Parts");
Vector3[] ObjectPositions = new Vector3[ExistingObjects.Length]

for(int i = 0; i < ObjectPositions.Length; i++)
{
   ObjectPositions[i] = ExistingObjects[i].transform.position;
   ObjectPositions[i].y = 0;
}