Reputation:
Here's my code
CustomClass.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;
}
MainClass.cs
string data = "";
void Start()
{
Scoreboard scoreBoard = new Scoreboard(data);
string s = string.Format ("{0}", scoreBoard);
Debug.Log ("The data is : " + s);
}
Why can't I display my string data to the console in Unity . Could someone help me please. Thank you.
Upvotes: 2
Views: 75
Reputation: 5920
You've the same names for input parameter and the member field of your class which prevents you from filling the correct one.
public Scoreboard(string data)
{
data = data; // << HERE
for(int i = 0; i < strData.Length; i++)
{
data += strData [i];
data += ",";
}
}
To fix your problem:
change the name of data
in your parameter to something else like 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;
}
rename member field called data
to something else like 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;
}
use this.data
whenever you want to refer to the member field:
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;
}
Upvotes: 1
Reputation: 1269
Your local variable is hiding your instance variable. Try:
public Scoreboard(string data)
{
this.data = data;
for(int i = 0; i < strData.Length; i++)
{
this.data += strData [i];
this.data += ",";
}
}
Upvotes: 1
Reputation: 2109
You need to reference the data
from the current instace of the class and not the data
passed in as a parameter.Use the this keyword. Your constructor should look like:
public Scoreboard(string data)
{
this.data = data;
for(int i = 0; i < strData.Length; i++)
{
this.data += strData [i];
this.data += ",";
}
}
Upvotes: 1