【问题标题】:Receive image from web server C# Unity从 Web 服务器 C# Unity 接收图像
【发布时间】:2017-05-11 16:23:15
【问题描述】:

我有存储图像的网络服务器。在 Unity 中,我可以接收一个并创建游戏对象来更改它的材质。但是,我想收到最大号码。四个图像。 1分钟后,我想收到最大号码。再来四张图。此外,如果服务器中有两个图像,我只想创建两个新的游戏对象并更改它们的材质。如果有三个,只需创建三个。我该怎么做,任何人都可以帮助我吗?这是我在 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;


    }



}

【问题讨论】:

    标签: c# unity3d server gameobject


    【解决方案1】:

    我会首先向我的服务器询问我可以获得的物品列表。为此,您可以简单地制作一个文本文件或制作您自己的 PHP 文件来创建一个列表,并用竖线 (|) 等字符分隔:

    MyMaterial1|MyMaterial2|MyMaterial3
    

    然后,您可以像获取图像一样从服务器询问文件,并从结果中创建一个 string[] 数组对象。您可以使用 Split('|') 从结果字符串创建此数组。

    完成后,您可以遍历数组中的项目。

    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);
        }
      }
    }
    

    最后但同样重要的是,您必须创建第二个函数,从您提供的字符串中加载纹理:

    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.
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-26
      相关资源
      最近更新 更多