Skip to content

Instantly share code, notes, and snippets.

@droganaida
Created November 12, 2017 11:41
Show Gist options
  • Save droganaida/bd5ff738f75e5e77017ae6feb2f1c201 to your computer and use it in GitHub Desktop.
Save droganaida/bd5ff738f75e5e77017ae6feb2f1c201 to your computer and use it in GitHub Desktop.
Unity3d C# ScrollView Adapter with Internet connection
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScrollViewAdapterConnected : MonoBehaviour {
public RectTransform prefarb;
public Text countText;
public RectTransform content;
public void UpdateItems ()
{
int modelsCount = 0;
int.TryParse(countText.text, out modelsCount);
string url = "http://127.0.0.1:6006?count=" + modelsCount;
WWW www = new WWW(url);
StartCoroutine(GetItems(www, results => OnReceivedModels(results)));
}
void OnReceivedModels (TestItemModel[] models)
{
foreach (Transform child in content)
{
Destroy(child.gameObject);
}
foreach (var model in models)
{
var instance = GameObject.Instantiate(prefarb.gameObject) as GameObject;
instance.transform.SetParent(content, false);
InitializeItemView(instance, model);
}
}
void InitializeItemView (GameObject viewGameObject, TestItemModel model)
{
TestItemView view = new TestItemView(viewGameObject.transform);
view.titleText.text = model.title;
view.clickButton.GetComponentInChildren<Text>().text = model.buttonText;
view.clickButton.onClick.AddListener(
()=>
{
Debug.Log(view.titleText.text + " selected!");
}
);
}
IEnumerator GetItems (WWW www, System.Action<TestItemModel[]> callback)
{
yield return www;
if (www.error == null)
{
TestItemModel[] mList = JsonHelper.getJsonArray<TestItemModel>(www.text);
Debug.Log("WWW Success: " + www.text);
callback(mList);
}
else
{
TestItemModel[] errList = new TestItemModel[1];
errList[0] = new TestItemModel();
errList[0].title = www.error;
errList[0].buttonText = "Game Over!";
Debug.Log("WWW Error: " + www.error);
callback(errList);
}
}
public class TestItemView
{
public Text titleText;
public Button clickButton;
public TestItemView (Transform rootView)
{
titleText = rootView.Find("TitleText").GetComponent<Text>();
clickButton = rootView.Find("ClickButton").GetComponent<Button>();
}
}
[System.Serializable]
public class TestItemModel
{
public string title;
public string buttonText;
}
public class JsonHelper
{
public static T[] getJsonArray<T>(string json)
{
string newJson = "{ \"array\": " + json + "}";
Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(newJson);
return wrapper.array;
}
public static string arrayToJson<T>(T[] array)
{
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.array = array;
return JsonUtility.ToJson(wrapper);
}
[System.Serializable]
private class Wrapper<T>
{
public T[] array;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment