NitroFray
NitroFray

Reputation: 43

Array deleting its previous content when I try to add more, in C# unity

I've recently started coding C# in unity to learn. There is still much code that I don't understand, arrays beeing one of them.

I'm trying to make a code that finds objects, counts them, and then store their positions in a Vector3 array.

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) };
}

When I have just one object in the scene, everything works. When I add more than that, it gets the first Vector3 from the first object it finds, and then deletes it when it puts the second Vector3 into the array. So all I'm left with (no matter how many objects I place in the scene) is ObjectPositions[0].

As I've already said, I'm fairly new to C# coding.

Upvotes: 0

Views: 81

Answers (3)

Ehsan Mohammadi
Ehsan Mohammadi

Reputation: 1228

Try this:

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;
}

Upvotes: 0

Gerco Brandwijk
Gerco Brandwijk

Reputation: 150

You are creating a new variable ObjectPositions in the loop. You should create this variable outside the loop and only add a Vector3 to this variable inside the loop.

This looks something like this:

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);
}

Upvotes: 4

Jack Gajanan
Jack Gajanan

Reputation: 1670

Use Generics instead

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));
}

Upvotes: 1

Related Questions