Reputation: 1
I'm following a Unity Cloud Save tutorial and I'm stuck in the following code.
#region Saved Games
//making a string out of game data (highscores...)
string GameDataToString()
{
return Mascota._monedas.ToString();
}
I do not know how to add more variables with the "return" in this structure. I do not understand well yet to use return.
Upvotes: 0
Views: 123
Reputation: 1438
If you have several variables, you can concatenate them.
An example:
int a = 123;
int b = 9999;
string c = "data";
string GameDataToString()
{
return a.ToString() + "; " + b.ToString() + "; " + c;
}
Which would yield following output:
123; 9999; data
There are many ways to concat strings:
"hello" + "; " + "world"
string var1 = "hello";
string var2 = "world";
string var3 = $"{var1}; {var2}";
String.Concat("hello", "; ", "world")
StringBuilder sb = new StringBuilder();
sb.Append("hello");
sb.Append("; ");
sb.Append("world");
sb.ToString();
Upvotes: 1
Reputation: 3326
There are two ways of doing this, using tuples (new feature in C# 7, which I have been able to get working on Unity) and using out
parameters.
C# 7 allows you to return
multiple values with their beautiful syntax:
public (string String1, string OtherString) GetStrings()
{
return ("This is String 1", "This is String 2");
}
...
Debug.Log(GetStrings().String1); // Logs "This is String 1"
Debug.Log(GetStrings().OtherString); // Logs "This is String 2
You don't need to specify the names when you set up the return type. This is exactly what you are looking for, but is tricky to setup (but worth it).
Then the "old school" way to get multiple returns is to use out
parameters, like so:
public void GetStrings(out string string1, out string otherString)
{
string1 = "This is String 1";
otherString = "This is String 2";
}
...
string string1;
string otherString;
GetStrings(out string1, out otherString);
Debug.Log(string1); // Logs "This is String 1"
Debug.Log(otherString); // Logs "This is String 2"
out
parameters can be done in Unity normally, but C# 7 adds out
variables.
Notice how we had to declare the variables first even though we weren't going to use them until after we called GetStrings()
? C# 7 allows us to simplify the code into:
public void GetStrings(out string string1, out string otherString)
{
string1 = "This is String 1";
otherString = "This is String 2";
}
...
GetStrings(out string string1, out string otherString); // Declaration for variables here
Debug.Log(string1); // Logs "This is String 1"
Debug.Log(otherString); // Logs "This is String 2"
And this'll work, but again, you need C# 7.
Upvotes: 0