# How can I duplicate a GameObject with the correct number of copies?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FormationsManager : MonoBehaviour
{
public int columns = 4;
public int gaps = 10;
public Formations formations;

private int numofmembers;
private List<GameObject> SquadMembers = new List<GameObject>();

// Use this for initialization
void Start()
{
}

// Update is called once per frame
void Update()
{
{
}

{
for (int i = 0; i < numberOfSquads; i++)
{
}
}
}

{

int i = 0;
for (; i < formations.newpositions.Count; i++)
{
else
go.transform.position = formations.newpositions[i];
go.transform.parent = gameObject.transform;
}

for (; i < SquadMembers.Count; i++)

}
}


In the Update I duplicate the squad:

if (numofsquads != numberOfSquads)
{
for (int i = 0; i < numberOfSquads; i++)
{
}
}


The problem is that if for example when running the game there is 1 squad and then I'm changing the value of numberOfSquads to 3 then instead duplicating more 2 squads it will duplicate more 3. And then if I will change the value of numberOfSquads from 3 to 4 it will add more 4 squads instead only 1.

And I also want to make that if I change the value of numberOfSquads to be lower then destroy the last squad/s.

In your loop you create a new squad for every numOfSquads. So if you want a total of 3 then you instantiate an extra 3.

if (numofsquads != numberOfSquads)

• Am I missing something or should this be i = numofsquads, and then set numofsquads = numberOfSquads at the end? Like this, it would instantiate one less gameobject than in the question, but have the same problem. – Christian Jun 29 '18 at 10:15