2016-09-01 3 views
0

Я хочу читать значения с моего веб-сервера в моей игре Unity, но я не получаю ответ, который я хочу. В принципе, подход, который я покажу, отлично работает для примитивных типов данных, но он не является, например, массивом объектов (имеет несколько значений int, возвращаемых из моей базы данных).C# ответ от веб-сервера пуст (Unity)

В Unity я это (полный код):

void Start() 
{ 
    string url = "http://example.com/unitygames/unitywebservice.asmx/GetGameData?='mygamename'"; 
    WWW www = new WWW(url); 
    StartCoroutine(WaitForRequest2(www)); 
} 


IEnumerator WaitForRequest2(WWW www) 
{ 
    yield return www; 

    if (www.error == null) 
    { 
     Debug.Log(www.text); 
    } 
    else 
    { 
      Debug.Log("Error " + www.text); 
    } 

И в C# Webservice Я делаю это:

[WebMethod] 
[ScriptMethod(UseHttpGet = true)] 
public List<Int32> GetGameData(string gameName) 
{ 

    List<Int32> myList = new List<Int32>(); 
    SqlConnection connection = new SqlConnection(SQL_CONNECTION); 
    String selectData = "SELECT STATEMENT HERE .."; 
    connection.Open(); 

    SqlCommand command = new SqlCommand(selectData, connection) 
    SqlDataReader reader = command.ExecuteReader(); 

    while (reader.Read()) { 

     myList.Add(reader.GetInt32(0)); 
     myList.Add(reader.GetInt32(1)); 
     myList.Add(reader.GetInt32(2)); 
     myList.Add(reader.GetInt32(3)); 
     myList.Add(reader.GetInt32(4)); 
     myList.Add(reader.GetInt32(5)); 
     myList.Add(reader.GetInt32(6)); 
     myList.Add(reader.GetInt32(7)); 

    } 
    connection.Close(); 
    return myList; 
} 

код на веб-службы часть работает нормально, так как я проверил это в браузере (он возвращает то, что я хочу), но в Unity я только получаю от этого www.text ответ:

<?xml version="1.0" encoding="utf-8"?> 
<ArrayOfInt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/" /> 
UnityEngine.Debug:Log(Object) 
<WaitForRequest2>c__Iterator1:MoveNext() (at Assets/Networking.cs:69) 

Так почему я не получить правильный ответ от www.text? Я что-то пропустил в самом Единстве?

EDIT: Фактические результаты из браузера

enter image description here

+0

Не могли бы вы разделить код на стороне клиента? –

+0

Конечно. Я редактировал свой код. – rootpanthera

+0

Какие результаты вы ожидаете или получаете при запуске в браузере. –

ответ

0

Try, чтобы вернуться от службы HttpResponseMessage ответ вместо простого списка:

[WebMethod] 
[ScriptMethod(UseHttpGet = true)] 
public HttpResponseMessage GetGameData(string gameName) 
{ 
    // Get data 
    List<Int32> myList = new List<Int32>(); 

    // ... 

    // Convert myList to JSON or XML string 
    // Example of simple JSON conversion for your case/better to use converter 
    var json = string.Format("[{0}]", myList.Select(x=>x.ToString()).Aggregate((x,y) => x + ", " + y)); 

    // Create response 
    var httpResponseMessage = new HttpResponseMessage(); 
    // Set content 
    httpResponseMessage.Content = json; 
    // Set headers content type 
    httpResponseMessage.Content.Headers.ContentType = = new MediaTypeHeaderValue("application/json"); // or "application/xml" 
    // Set status 
    httpResponseMessage.StatusCode = HttpStatusCode.OK; 

    return httpResponseMessage; 
} 

И тогда вы должны подождать до скачивания ответа от сервера завершено:

public string url = "http://example.com/unitygames/unitywebservice.asmx/GetValues"; 

    IEnumerator Start() { 
     // Start a download of the given URL 
     WWW www = new WWW(url); 

     // Wait for download to complete 
     yield return www; 

     // Read the www.text 
    } 
+0

Да, это довольно просто. У меня уже есть это в моем коде. – rootpanthera

+0

Хорошо, я обновил свой ответ с образцом кода сервера, который использует HttpResponseMessage. –

Смежные вопросы