public class PlacesScreen : MonoBehaviour
{
// Used to check if the screen resolution changed
// TODO : Find a better solution than this one
public float startWidth;
public float startHeight;
List<Place> places;
UIScrollView PlacesList;
UIGrid PlacesGrid;
GameObject FileList;
// Hardcoded for testing purposes only
string json = @"[{ blabla
}]";
// Use this for initialization
void Start()
{
places = JsonConvert.DeserializeObject<List<Place>>(json);
PlacesList = gameObject.GetComponentInChildren<UIScrollView>() as UIScrollView;
PlacesGrid = gameObject.GetComponentInChildren<UIGrid>() as UIGrid;
FileList = GameObject.Find("Grid");
startHeight = PlacesList.gameObject.GetComponent<UIPanel>().height;
startWidth = PlacesList.gameObject.GetComponent<UIPanel>().width;
if (PlacesGrid != null && FileList != null && PlacesList != null)
{
BetterList<Transform> childList = PlacesGrid.GetChildList();
// Addind the places from the json to the graphic list
foreach (Place place in places)
{
Debug.Log("Adding a place");
GameObject placeFile = Resources.Load("prefabs/File") as GameObject;
placeFile.GetComponent<UISprite>().width = (int)PlacesGrid.cellWidth;
placeFile.transform.Find("ContentPanel").gameObject.transform.Find("PlaceName").gameObject.GetComponent<UILabel>().text = place.Name;
placeFile.transform.Find("ContentPanel").gameObject.transform.Find("CityName").gameObject.GetComponent<UILabel>().text = place.City;
placeFile.transform.Find("ContentPanel").gameObject.transform.Find("TypeName").gameObject.GetComponent<UILabel>().text = place.Type;
NGUITools.AddChild(FileList, placeFile);
childList.Add(placeFile.transform);
}
// Small hack to get a nicely presented Grid even with only 1 element
// TODO : Redo this ...
if (childList.size == 1)
{
Debug.Log("One place only, we have to had a invisible file to avoid center");
GameObject invisibleFile = Resources.Load("prefabs/File") as GameObject;
NGUITools.AddChild(FileList, invisibleFile);
childList.Add(invisibleFile.transform);
}
ResizeGrid();
}
}
// Update is called once per frame
void Update()
{
if (startHeight != PlacesList.gameObject.GetComponent<UIPanel>().height || startWidth != PlacesList.gameObject.GetComponent<UIPanel>().width)
{
ResizeGrid();
startHeight = PlacesList.gameObject.GetComponent<UIPanel>().height;
startWidth = PlacesList.gameObject.GetComponent<UIPanel>().width;
}
}
/// <summary>
/// Resize the grid considering the screen width
/// </summary>
void ResizeGrid()
{
Debug.Log("ResizeGrid Called");
// Resizing the Grid cells' size.
PlacesGrid.cellWidth = (float)(PlacesList.gameObject.GetComponent<UIPanel>().width / 2.2);
PlacesGrid.cellHeight = (float)(PlacesGrid.cellWidth / 1.244);
foreach (Transform place in PlacesGrid.GetChildList())
{
place.gameObject.GetComponent<UISprite>().width = (int)PlacesGrid.cellWidth;
}
PlacesGrid.Reposition();
PlacesList.ResetPosition();
}
}