MD5 GetHash仅适用于Unity Editor?

时间:2015-05-05 14:08:53

标签: c# android unity3d md5

我正在制作Android游戏,有代码可以将高分信息发送到我的网站的PHP代码。

奇怪的是,这在Unity编辑器中运行良好,但是在我制作了一个.apk并在真正的Android手机上运行之后,它就无法运行并且会出错。

错误如下(Eclipse logcat已知)

  

05-05 22:56:47.997:I / Unity(20561):NullReferenceException:Object   引用未设置为对象的实例05-05 22:56:47.997:   I / Unity(20561):at HighScore.GetHash(System.String usedString)   [0x00000] in:0 05-05 22:56:47.997:I / Unity(20561):   在HighScore + c__Iterator14.MoveNext()[0x00000] in   :0

代码是首次运行高分时注册昵称的功能。

 public IEnumerator RegisterName(string name)
{ 
    string finalResult = "";
    string tables = "";
    for (int m = 0; m < difficultyModes.Length; m++)
    {//Create a list of tables to send 
        if (m < difficultyModes.Length - 1)
        {
            tables += difficultyModes[m].databaseName + " ";
        }
        else
        {
            tables += difficultyModes[m].databaseName;
        }
    } 
    WWWForm rsFm = new WWWForm();
    rsFm.AddField("name", name);
    rsFm.AddField("tables", tables);
    rsFm.AddField("hash", GetHash(name));
    WWW rs = new WWW(registerUserURL, rsFm);
    yield return rs;
    Debug.Log(rs.text + " : " + difficultyModes[modeIndex].displayName);
    finalResult = rs.text;
    if (finalResult.Equals("Already Used"))
    {
        runningHsServer = 0;
        status = "Name Already Used";
        TitleScript.Instance.PopupMsgWithNoBack("Name is already taken.", true);
        yield break;
    }
    else if (finalResult.Equals("Registration Complete"))
    {//We Registered Now Update Score
        PlayerPrefs.SetInt("nameRegistered", 1);
        PlayerPrefs.SetString("registeredName", name);
        TitleScript.Instance.PopupMsgWithNoBack("Name registered!", true);
        TitleScript.Instance.PopupNo();
        NewUI.Instance.myNick.text = name;
        myNickName = name;
        NewUI.Instance.OpenHigh();
    }
    else
    {
        runningHsServer = 0;
        status = finalResult; yield break;
    }

}

和GetHash部分。 (此处出现NullReference错误)

string GetHash(string usedString)
{ //Create a Hash to send to server
    MD5 md5 = MD5.Create();
    //byte[] bytes = Encoding.ASCII.GetBytes(usedString+secretKey);     // this wrong because can't receive korean character
    byte[] bytes = Encoding.UTF8.GetBytes(usedString + secretKey);
    byte[] hash = md5.ComputeHash(bytes);

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < hash.Length; i++)
    {
        sb.Append(hash[i].ToString("x2"));
    }
    return sb.ToString();
}

2 个答案:

答案 0 :(得分:5)

使用MD5CryptoServiceProvider代替MD5.Create()

var md5 = new MD5CryptoServiceProvider();

当Stripping Level设置为Micro mscorlib时,MD5.Create()不会在Unity Android上返回对象,但是'new MD5CryptoServiceProvider()'。

答案 1 :(得分:0)

所以这是因为统一构建设置的剥离级别设置。

最初我设置了最大的strippied设置(使用micro mscorlib)来获得更小的.apk文件大小,但这阻止了一些代码功能。

所以我把它设置为Disabled,上面的功能也可以在Android手机上正常工作。