Lists not working in an appropriate way,Lists applying to everything in for loop
Hi there,
I am trying to recurse through a bunch of GameObjects in a list:
// get the relative position of the weapons to the ship
List<Transform> weaponPositions = ship.GetWeaponLocations(); // works
// set the positions of the weapons
for(int i = 0 ; i < equippedWeapons.Length && i < weaponPositions.Count ; i++)
{
equippedWeapons[i].GetComponent<Weapon>().setPosition(weaponPositions[i]);
}
However it seems to apply the last 'weaponPositions' to everything. So weaponPositions is a list of type Transform, and I want to set the position of weapon[0] to the position of weaponPosition[0] for example.
The problem is that when it gets to the third weapon (the last in this case), it applies the weaponPosition[2] position to each of the weapons that has come before, not just the i'th index.
The weapons are a SerailizedField:
[SerializeField] GameObject[] equippedWeapons;
In weapon the setWeapon method is simply:
Transform positionOfWeaponOnShip;
public void setPosition(Transform pos)
{
positionOfWeaponOnShip = pos;
}
The question I am asking is, am I using the List in the correct way here? Im stumped as to why it isnt only applying this to the i'th value. Im also not sure what else I can put here which would be useful...
Thanks, Bogo
Answer by highpockets · Apr 22, 2019 at 11:37 AM
The setPosition method is not setting a position, it is setting a Transform. A transform has a Vector3 property named position which is what you want to apply. If you want to set the position here, you will have to change the Transform parameter to a Vector3 parameter and set the 3 floats relating to xyz coordinates in the Vector3 when you call it.
Hi @highpockets,
Thanks for the reply - it turned out the problem was that I was referring to an object each time, and not an instance of an object. I had to instantiate three weapons and set them manually - now they work :)
Thanks again, Bogo