You've successfully subscribed to Hacking with Unity - Learn how to create your own games
Great! Next, complete checkout for full access to Hacking with Unity - Learn how to create your own games
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

String in Unity using C#


In Unity, you can either use string or System.String for the string variable.

public class PlayerControl : MonoBehaviour {
    void Awake() {
        // define a string
        string s = "foo";
        Debug.Log(s);   // output: foo

        // string format
        s = string.Format("{0} {1}", s, "bar");
        Debug.Log(s);   // output: foo bar

        // to uppercase
        s = s.ToUpper();
        Debug.Log(s);   // output: FOO BAR

        // to lowercase
        s = s.ToLower();
        Debug.Log(s);   // output: foo bar

        // concat two string
        s = string.Concat("foo", "bar");
        Debug.Log(s);   // output: foobar

        // get character from index
        Debug.Log(s[0]);    // output: f

        // ToString() function basically can convert any number to string
        // convert int to string,
        int i = 10;
        s = i.ToString();
        Debug.Log(s);   // output: "10"

        // convert string to int
        s = "100";
        i = int.Parse(s);
        Debug.Log(i);   // output: 100

        s = "abc";
        i = int.Parse(s);
        //error FormatException: Input string was not in a correct format.