简体   繁体   中英

Receive image from web server C# Unity

I have had web server that stores the images. In Unity, I can receive one and create gameobject to change it's material. However, I want to receive max no. four images. After 1 mins, I want to receive max no. four images again. Besides, if there is two images in server, I just want to create two new gameobject and change them material. If there is three, just create three. How can I do that, Any one can help me? Here is my code in Unity:

void Start () {
    StartCoroutine (LoadImage ());
}

IEnumerator LoadImage(){

    filename = "image" + k.ToString () + ".png";
    url = "https://wwwfoodparadisehk.000webhostapp.com/" + filename;
    WWW www = new WWW (url);
    yield return www;

    if (www.error != null) {
        Debug.Log (www.error);
    } else {


        Debug.Log (k);


        path = "Assets/MyMaterial" + k.ToString () + ".mat";

        k = k + 1;

        material = new Material (Shader.Find ("Sprites/Default"));
        AssetDatabase.CreateAsset (material, path);

        Debug.Log (AssetDatabase.GetAssetPath (material));

        material.mainTexture = www.texture;
        GameObject newPaperInstance = Instantiate (newpaper) as GameObject;
        newPaperInstance.transform.Find ("Plane001").gameObject.GetComponent<Renderer> ().material = material;


    }



}

I'd first ask my server for a list of the items I can get. For this, you can simply make a text file or make your own PHP file to create a list that you separate by a character like the pipe (|):

MyMaterial1|MyMaterial2|MyMaterial3

Then you can ask the file from your server the same way you'd get the images and create a string[] array object from the result. You can use Split('|') in order to create this array from your result string.

When you're done, you can foreach over the items within the array.

IEnumerator LoadImages()
{
  string filename = "imagelist.txt";
  string url = "https://wwwfoodparadisehk.000webhostapp.com/" + filename;
  WWW www = new WWW (url);
  yield return www;

  if (www.error != null) 
  {
    Debug.Log (www.error);
  } 
  else 
  {
    string[] images = www.text.Split ('|');
    foreach (var image in images) 
    {
      LoadImage (image);
    }
  }
}

Last but not least, you'll have to create a second function that loads the texture from the string you supply:

IEnumerator LoadImage(string image)
{
  string url = "https://wwwfoodparadisehk.000webhostapp.com/" + image;
  WWW www = new WWW (url);
  yield return www;

  if (www.error != null) 
  {
    Debug.Log (www.error);
  } 
  else 
  {
    // turn your image into a texture with www.texture and apply it to your objects.
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM