自定义类无法显示2d数组c#(统一)

时间:2018-05-30 15:10:44

标签: c# unity3d

这是我的代码

CustomClass.cs

sum(bvtw[0], ...)

MainClass.cs

public string[,] tableBR{ get; set; }

string[] strData = {"P  ,B  ,B  ,P  ,B  ,B  ,B  ,B  ,B  ,B  ,P  ,P  ,B  ,P  "};
string data = "";
public int X_LENGTH = 104;
public int Y_LENGTH = 15;

public Scoreboard(string data)
{
    data = data;
    for(int i = 0; i < strData.Length; i++)
    {
        data += strData [i];
        data += ",";
    }
}

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

为什么我不能在Unity中向控制台显示我的字符串数据。请有人帮助我。谢谢。

3 个答案:

答案 0 :(得分:1)

您需要引用该类当前实例中的data而不是作为参数传入的data。使用this关键字。您的构造函数应如下所示:

public Scoreboard(string data)
{
    this.data = data;
    for(int i = 0; i < strData.Length; i++)
    {
        this.data += strData [i];
        this.data += ",";
    }
}

答案 1 :(得分:1)

您的本地变量正在隐藏您的实例变量。尝试:

public Scoreboard(string data)
{
    this.data = data;
    for(int i = 0; i < strData.Length; i++)
    {
        this.data += strData [i];
        this.data += ",";
    }
}

答案 2 :(得分:1)

您输入参数和类的成员字段的名称相同,这会阻止您填写正确的名称。

public Scoreboard(string data)
{
    data = data; // << HERE
    for(int i = 0; i < strData.Length; i++)
    {
        data += strData [i];
        data += ",";
    }
}

解决问题:

  • 将参数中data的名称更改为dataInput之类的其他内容:

    public string[,] tableBR{ get; set; }
    
    string[] strData = {"P  ,B  ,B  ,P  ,B  ,B  ,B  ,B  ,B  ,B  ,P  ,P  ,B  ,P  "};
    string data = "";
    public int X_LENGTH = 104;
    public int Y_LENGTH = 15;
    
    public Scoreboard(string dataInput)
    {
        data = dataInput;
        for(int i = 0; i < strData.Length; i++)
        {
            data += strData [i];
            data += ",";
        }
    }
    
    public override string ToString()
    {
        return "this are all the data :" + data;
    }
    
  • 将名为data的成员字段重命名为dataInput之类的其他内容:

    public string[,] tableBR{ get; set; }
    
    string[] strData = {"P  ,B  ,B  ,P  ,B  ,B  ,B  ,B  ,B  ,B  ,P  ,P  ,B  ,P  "};
    string dataInput = "";
    public int X_LENGTH = 104;
    public int Y_LENGTH = 15;
    
    public Scoreboard(string data)
    {
        dataInput = data;
        for(int i = 0; i < strData.Length; i++)
        {
            dataInput += strData [i];
            dataInput += ",";
        }
    }
    
    public override string ToString()
    {
        return "this are all the data :" + dataInput;
    }
    
  • 每当您想要引用成员字段时使用this.data

    public string[,] tableBR{ get; set; }
    
    string[] strData = {"P  ,B  ,B  ,P  ,B  ,B  ,B  ,B  ,B  ,B  ,P  ,P  ,B  ,P  "};
    string data = "";
    public int X_LENGTH = 104;
    public int Y_LENGTH = 15;
    
    public Scoreboard(string data)
    {
        this.data = data;
        for(int i = 0; i < strData.Length; i++)
        {
            this.data += strData [i];
            this.data += ",";
        }
    }
    
    public override string ToString()
    {
        return "this are all the data :" + this.data;
    }