无法将JsonObject中的字符串转换为Unity中的float

时间:2019-12-05 20:03:21

标签: c# json unity3d type-conversion

我正在使用'Socket.IO for Unity'插件,并使用JSONObject将数据发送到服务器,但是我无法从字符串转换为float。

使用:

Debug.Log(e.data.GetField("vertical").ToString());

正确返回字符串"0,978"

但是'float.Parse'可以与除JsonObject之外的任何字符串一起使用,例如采用上面的JsonObject字符串并使用float.Parse:

float.Parse (e.data.GetField("vertical").ToString())

只需中断其余代码,而不会出现任何控制台错误,游戏就可以完美进行,但不会返回浮动值! 可能会发生什么?有人有什么想法吗?

我的代码:

public void PlayerAnim(SocketIOEvent e){
    if(e.data.GetField("id").ToString () == id){
        anim.SetFloat ("IsRunning", Mathf.Abs (float.Parse (e.data.GetField("vertical").ToString()) + Mathf.Abs (float.Parse (e.data.GetField("horizontal").ToString()))));
    }
}

3 个答案:

答案 0 :(得分:1)

您可以使用逗号作为分隔符。

摘录自here

var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.NumberFormat.NumberDecimalSeparator = ",";

// If this is supposed to return a value from a method, use return
return float.Parse (e.data.GetField("vertical").ToString(), culture);

编辑:

public void PlayerAnim(SocketIOEvent e){
    var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
    culture.NumberFormat.NumberDecimalSeparator = ",";

    if(e.data.GetField("id").ToString () == id){
        anim.SetFloat ("IsRunning", Mathf.Abs (float.Parse (e.data.GetField("vertical").ToString(), culture) + Mathf.Abs (float.Parse (e.data.GetField("horizontal").ToString(), culture))));
    }
    else 
    {
      // Throw or some other statement to see if id does not match
    }
}

答案 1 :(得分:1)

您需要使用JSONObject扩展。有一个f扩展名可以为您提取一个浮动对象。

服务器:

socket.emit('hello', {float: 0.978});

团结:

socket.On ("hello", (message) => {
   var myValue = message.data.GetField("float").f; 
   // or var myValue = message.data["float"].f;
});

资产真的很旧,使用默认JSONObject类存在问题,因为我记得它会在序列化/解析期间吞下错误。值得一看的是Best HTTP 2资产,该资产会定期更新。

但是,即使进行了额外的强制转换,您的代码仍然可以工作,并且会设置断点,并且只需对float.Parse (e.data.GetField("vertical").ToString())语句进行评估即可。

答案 2 :(得分:0)

默认格式提供程序期望.作为十进制标记。您可以通过提供适当的IFormatProvider

来用逗号来解析浮点数
float.Parse (e.data.GetField("vertical").ToString(), System.Globalization.CultureInfo.GetCultureInfo("de-DE"));