Hey all. I’m trying to set up a script that instantiates multiple objects of the same type in different stored positions with different stored rotations. I feel like I’m really close, but I’m having trouble with this one issue. I find all the objects of class Barrel in the scene, then store that in an array. I then go through a foreach loop, adding every position of that barrel to a list of barrelPositions. After that, I set up another foreach loop function, this time instantiating a barrelPrefab at every barrelPosition on the list, but since different barrels have unique positions, I’m trying to find the index of the local variable barrel and then use that index in the barrelPositions list for use in Instantiation.
Any help? Here’s the relevant snippets of my code.
Barrel[] barrels;
Target[] targets;
Vector3 barrelStartPos;
Vector3 targetStartPos;
Quaternion barrelStartRotation;
Quaternion targetStartRotation;
List<Vector3> barrelPositions = new List<Vector3>();
List<Quaternion> barrelRotations = new List<Quaternion>();
List<Vector3> targetPositions = new List<Vector3>();
List<Quaternion> targetRotations = new List<Quaternion>();
void Start {
//find all barrels, then save their positions to the barrelPositions list
barrels = FindObjectsOfType<Barrel>();
foreach (Barrel barrel in barrels)
{
barrelStartPos = barrel.transform.position;
barrelPositions.Add(barrelStartPos);
}
//find all barrels, then save their rotations in the same order as barrelPositions
foreach (Barrel barrel in barrels)
{
barrelStartRotation = barrel.transform.rotation;
barrelRotations.Add(barrelStartRotation);
}
}
public void RespawnObjects()
{
//instantiate every barrel with the same rotation and positions as those with the same index in their respective lists
foreach (Barrel barrel in barrels)
{
//int barrelIndex = barrels.index //here's the annoying part
Instantiate(barrelPrefab, barrelPositions.barrelIndex, barrelRotations.barrelIndex);
}`