Can anybody tell me where i have gone wrong, I am trying to instantiate prefabs to a grid layout group component and for any given variable of slots i try to create i get a extra 50% of that given number that are unparented clones of clones,, i.e if i want to create 10 slots it will add 10 slots to the inventory grid but it will spawn 5 unparented clones of clones ,20 will spawn 10 unparented unwanted clones
public class SlotControl : MonoBehaviour
{
public GameObject inventorySlotPrefab;
public Transform inventoryGrid;
public int MaxSlots;
[SerializeField]private int currentNumberOfSlots;
private void Start()
{
//CountSlots();
//if (currentNumberOfSlots != MaxSlots)
//{
// SlotCreation();
//}
}
private void Update()
{
//if (MaxSlots != currentNumberOfSlots)
//{
// SlotCreation();
//}
if (Input.GetKeyDown(KeyCode.Return))
{
if (MaxSlots != currentNumberOfSlots)
{
Debug.Log("Forced Update");
SlotCreation();
}
}
}
public void CountSlots()
{
{
GameObject[] _inventorySlotPrefab = GameObject.FindGameObjectsWithTag("inventorySlotPrefab");
Debug.Log("Found Slot Tags");
currentNumberOfSlots = _inventorySlotPrefab.Length;
Debug.Log("Slots Counted");
}
}
public void SlotCreation()
{
CountSlots();
for (int i = 0; i < MaxSlots; i++)
{
//var obj = inventorySlotPrefab.transform;
var obj = Instantiate(inventorySlotPrefab, Vector3.zero, Quaternion.identity, transform);
obj.transform.SetParent(inventoryGrid.transform);
if (currentNumberOfSlots < MaxSlots)
{
Debug.Log("Not Enough Slots");
Instantiate(obj);
CountSlots();
}
else if(currentNumberOfSlots > MaxSlots)
{
Debug.Log("Too Many Slots");
Destroy(obj);
CountSlots();
}
else if(currentNumberOfSlots == MaxSlots)
{
Debug.Log("Slot Count OK");
}
}
}
}
↧