无法从自定义类中打印foreach值

时间:2018-05-30 17:39:16

标签: c# unity3d

到目前为止,这是我的代码

CUSTOMCLASS.CS

public string[,] tableBR;

string[] strData = {"P  ,B  ,B  ,P  ,B  ,B  ,B  ,B  ,B  ,B  ,P  ,P  ,B  ,P  "};

public int X_LENGTH = 104;
public int Y_LENGTH = 15;

#region BR VARIABLES

string BigRD= "";
string[] newBigRD;
string realData= "";

#endregion
public Scoreboard(){
    tableBR= new string[X_LENGTH,Y_LENGTH   ];
}

public void MakeBR(string data){
    BigRD = data;

    for(int i = 0; i < strData.Length; i++){
        BigRD += strData [i];
        BigRD += ",";
    }

    newBigRD= BigRD .Split (',');

    foreach(string newData in newBigRD){
        realData = newData;
    }
}

public string ShowBigRD(){
    return realData;
}

public override string ToString(){
    return "this are all the data :" + realData.ToString();
}

这是我的主要课程

MAINCLASS.CS

string BigRD= "";

void Start(){
    StartCoroutine ("Win_Log");
}

IEnumerator Win_Log(){
    Scoreboard scoreBoard = new Scoreboard();

    scoreBoard.MakeBR(BigRD);
    Debug.Log ("This is the data : " + scoreBoard.ShowBigRD());

    yield return new WaitForEndOfFrame ();
}

它给了我一个空字符串值。它只打印

  

“这是所有数据:”

2 个答案:

答案 0 :(得分:2)

简单如改变

realData += newData;

string realData

否则,您每次都会在循环中覆盖{{1}},而不是仅仅追加它。

答案 1 :(得分:2)

我猜你正在寻找这个:

IEnumerator Win_Log()
{    
    Scoreboard scoreBoard = new Scoreboard();   
    scoreBoard.MakeBigRoad (BigRD);    

    for(int i=0; i< scoreBoard.newBigRD.Length;i++)
    {
        var realData = scoreBoard.newBigRD[i];
        Debug.Log ("This is the data : " + realdata); 
    }

    yield return new WaitForEndOfFrame ();
}

如果您决定这样做,则必须将字符串[],string[] newBigRD;设为公开,方法是将其更改为public string[] newBigRD;,以便在课堂外访问它。

您也可以修复字符串数组声明。它看起来应该是这样的,

string[] strData = {"P" ,"B ","B","P","B","B","B","B","B","B","P","P","B","P"};

或者我们可以保留您正在使用的分割方法并使用

newBigRD[]:

我在我的例子中使用了这个。

Options for initializing a string array