Hello,
first of all sorry for my bad english.
I have a list of 2 hundred items, and I need to instantiate only partial content at a time and remove the previous rows as they disappears to user.
Im new to unity, I successfully created a scene with
Main Camera
UI Root
Scroll View
Grid
I attach 'Manager.cs' to MainCamera, and at start it load list of items into an array, then add the first 20 items to Grid
This script should also add more rows as the Grid scroll
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Manager : MonoBehaviour {
public Transform panel;
public int total = 200;
public GameObject parent;
public GameObject itemPrefab;
public UIScrollView ScrollView;
public UIGrid Grid;
public float cellWidth = 150;
public float cellHeight = 40;
public int bundle = 20;
public float posY = 0f;
List<GameObject> preLoadedItemList;
GameObject[] itemList;
// Use this for initialization
void Start () {
// Preloaded list of items, loaded in some way
preLoadedItemList
= new List
<GameObject
>(); for (int i = 0; i<= total; i++) {
preLoadedItemList.Add(itemPrefab);
}
// list of visible items
itemList
= new GameObject
[total
];
// the first 20 visible items
for(int i = 0; i<= bundle; i++)
{
AddItem(i);
}
}
void AddItem(int seq){
if (seq < 0 || seq >= total) {
Debug.Log("Exit 1");
return;
}
if (itemList[seq]) {
Debug.Log("Exit 2 seq: "+seq);
return;
}
GameObject item = NGUITools.AddChild(parent, preLoadedItemList[seq]);
Grid.GetComponent<UIGrid>().Reposition();
ScrollView.ResetPosition();
itemList[seq] = item;
}
// check if I need to add another item into grid
void Update ()
{
// Debug.Log ("height panel: "+panel.localPosition.y); // all times 236
/* not working */
/*
posY = panel.localPosition.y;
int pos = Mathf.Abs(Mathf.FloorToInt(posY / cellHeight));
Debug.Log ("POS: "+pos);
for (int i = -1; i < bundle; i++)
{
int seq = i + pos;
AddItem(i + pos);
}
*/
}
}
I Attach a second script to my prefabs, 'Item.cs'
The rule of Item.cs should be to remove itself (the row) when it disappear from the camera
using UnityEngine;
using System.Collections;
public class Item : MonoBehaviour {
Transform tr;
private float min = -400, max = 30;
[HideInInspector]
public bool on = false;
Transform panel;
void Start()
{
tr = transform;
panel = transform.parent;
}
void OnOutside()
{
Destroy(gameObject);
}
void Update()
{
Vector3 pos = tr.localPosition;
if (pos.y > max || pos.y < min)
{
OnOutside();
}
}
}
In the Update method I am not able to calculate when I should add a new row, could someone help me with this problem ?
Any help would be appreciated..
Thanks in advance!!