Skip to content

Instantly share code, notes, and snippets.

@ricardj
Created December 11, 2022 19:19
Show Gist options
  • Save ricardj/08119a43948b860257a24f65e15db642 to your computer and use it in GitHub Desktop.
Save ricardj/08119a43948b860257a24f65e15db642 to your computer and use it in GitHub Desktop.
Script for spawning list items on UI in Unity.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GUIList<T> : MonoBehaviour where T : MonoBehaviour
{
[Header("GUI List configuration")]
[SerializeField] T _itemPrefab;
[Header("GUI List debug")]
[SerializeField] List<T> _listItems;
[SerializeField] Transform _parentTransform;
public void ClearTransform()
{
foreach (Transform child in _parentTransform.transform)
{
Destroy(child.gameObject);
}
_listItems.Clear();
}
public List<T> AdaptChild(int amount)
{
int currentItems = _listItems.Count;
if (currentItems < amount)
{
int difference = amount - currentItems;
for (int i = 0; i < difference; i++)
{
SpawnNewItem();
}
}else
{
ClearTransform();
AdaptChild(amount);
}
return _listItems;
}
private void SpawnNewItem()
{
T newItemPrefab = Instantiate(_itemPrefab, _parentTransform);
_listItems.Add(newItemPrefab);
}
public List<T> RefreshCompletely(int amount)
{
ClearTransform();
return AdaptChild(amount);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment