I'm trying to recreate android's RecyclerView on Unity using ScrollRect and Unity's object pooling system. I was able to make it work great when scrolling using the mouse, but when I drag up and down (for mobile) it just loads everything down very fast. I think this has something to do with using the scrollbar's value and not being able to set it to 0.5 after dragging, but I'm not sure how to replicate how a RecyclerView does it.
public void OnScrollUpdate()
{
if(_scrollbar.value <= 0.4f) //if the user scrolls down slightly, load forward
{
StartCoroutine(LoadForward()); //After loading forward, _scrollbar.value is set to 0.5f again
}
else if(_scrollbar.value >= 0.6f) //if the user scrolls up slightly, load backward
{
StartCoroutine(LoadBackward()); //After loading backward, _scrollbar.value is set to 0.5f
}
}
//Loads one card down and unloads the top card. The opposite is for Loadbackward
public IEnumerator LoadForward()
{
var newItem = _pool.Get();
newItem.transform.SetAsFirstSibling();
yield return new WaitForEndOfFrame();
_pool.Release(inventoryParent.transform.GetChild(0));
}
OnScrollUpdate listens to the value change of the scrollbar. The logic here is just that if the user scrolls down, loads more cards down, and unloads the cards above. Vice versa for scrolling up.
I've tried the following but probably did it wrong:
- Call the above function OnDragEnd instead of on scroll update (the user will reach the bottom if I do this)
- Call the above function OnDrag
- Make it scroll only once OnDrag and wait for OnDragEnd to be triggered before being able to scroll again (the user will still reach the bottom)
Send help!