Unity ArgumentOutOfRangeException:参数超出范围。参数名称:i

时间:2017-02-13 00:41:37

标签: c# regex

我收到此错误:

ArgumentOutOfRangeException: Argument is out of range.
Parameter name: i
   System.Text.RegularExpressions.MatchCollection.get_Item (Int32 i)
   ServerTime.SplitString (UnityEngine.WWW www) (at Assets/Script/Common/ServerTime.cs:48)
   ServerTime+<GetTime>c__IteratorB.MoveNext () (at Assets/Script/Common/ServerTime.cs:31)

错误链接:

time = string.Format("{0}:{1}:{2} {3}:{4}:{5}"

我的代码:

using UnityEngine;
using System.Collections;
using System.Text.RegularExpressions;

public class ServerTime : MonoBehaviour{

private string url = "http://www.beijing-time.org/time.asp";
private string time = string.Empty;

public delegate void GetTimeBackCall(string time);
private static GetTimeBackCall call;

public void GetServerTime(GetTimeBackCall backCall) 
{
    call = backCall;
    StartCoroutine("GetTime");

}

public IEnumerator GetTime()
{
    //Debug.Log("Start Requesting server time");

    while (true) 
    {
        WWW www = new WWW(url);
        yield return www;                   //Blocked here, waiting for a response after the return
        if (www.isDone && string.IsNullOrEmpty(www.error) && www.text.Length >= 10)
        {
            SplitString(www);
            break;
        }
        //Debug.Log("Re-request the server time");
    }

    yield return new WaitForFixedUpdate();
}

private void SplitString(WWW www)
{
    //Use regular matching expression
    string patten = @"[0-9]{1,};";
    Regex regex = new Regex(patten);
    MatchCollection result = regex.Matches(www.text);

    //Time Organizational
    time = string.Format("{0}:{1}:{2} {3}:{4}:{5}"
                         , result[0].Value.TrimEnd(';')
                         , result[1].Value.TrimEnd(';')
                         , result[2].Value.TrimEnd(';')
                         , result[3].Value.TrimEnd(';')
                         , result[4].Value.TrimEnd(';')
                         , result[5].Value.TrimEnd(';')
                         );


    if(time.Length >= 10)
    {
        call(time);
    }

    //Debug.Log("EU:" + time);
}
}

1 个答案:

答案 0 :(得分:0)

您的问题出在SplitString()方法中。该方法存在各种潜在问题,包括空引用问题,因此清理此方法对长期有用。

以下是如何解决您的特定问题的示例。由于你不知道你的正则表达式切换传入的值有多少元素,你最好循环它们而不是假设你有六个。这应该原则上有效;我没有测试就输入了这个:

private void SplitString(WWW www)
{
    // Use regular matching expression.
    MatchCollection result = new Regex(@"[0-9]{1,};").Matches(www?.text ?? string.Empty);

    // Time Organizational. (if you used a StringBuilder it could be a touch faster)
    string time = string.Empty;
    foreach (var item in result) // Loop through all results no matter how many.
        time += time + item.Value.TrimEnd(';') + ":";
    time = time.TrimEnd(':'); // Get rid of the last unnecessary colon.

    // Unsure what this does, but your original code contained it.
    if(time.Length >= 10)
        call(time);
}

P上。 S.如果您编写了单元测试,那么您自己就会发现问题; - )