Created
December 11, 2022 19:19
-
-
Save ricardj/08119a43948b860257a24f65e15db642 to your computer and use it in GitHub Desktop.
Script for spawning list items on UI in Unity.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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