Represents text as a series of Unicode characters.
Unity uses the .Net System.String
class for strings. See the Microsoft MSDN
documentation for Strings
for more details.
Note: In c# string
is an alias for System.String
. This means that you
can use either string
or String
in your code (if you have added using System
to the top of your script.)
Note: In Javascript strings are represented using String
which you should use
in your Unity script code.
Here are some basic uses of the String class.
using UnityEngine; using System.Collections;
public class ExampleClass : MonoBehaviour { void Start() { // prints hello string s = "hello"; Debug.Log(s);
// prints hello world s = string.Format("{0} {1}", s, "world"); Debug.Log(s);
// prints helloworld s = string.Concat("hello", "world"); Debug.Log(s);
// prints HELLOWORLD s = s.ToUpper(); Debug.Log(s);
// prints helloworld s = s.ToLower(); Debug.Log(s);
// prints 'e' Debug.Log(s[1]);
// prints 42 int i = 42; s = i.ToString(); Debug.Log(s);
// prints -43 s = "-43"; i = int.Parse(s); Debug.Log(i);
// prints 3.141593 (an approximation) float f = 3.14159265359F; s = f.ToString(); Debug.Log(s);
// prints -7.141593 (an approximation) s = "-7.14159265358979"; f = float.Parse(s); Debug.Log(f); } }
This example shows how you can examine the String class and see the methods it contains.
using System; using System.Reflection; using UnityEngine; using System.Collections;
public class ExampleClass : MonoBehaviour { void Start() { Type t = typeof(System.String);
// Iterate over all the methods from the System.String class and display // return type and parameters. // This reveals all the things you can do with a String. foreach (MethodInfo mi in t.GetMethods()) { System.String s = System.String.Format("{0} {1} (", mi.ReturnType, mi.Name); ParameterInfo[] pars = mi.GetParameters();
for (int j = 0; j < pars.Length; j++) { s = String.Concat(s, String.Format("{0}{1}", pars[j].ParameterType, ((j == pars.Length - 1) ? "" : ", "))); } s = String.Concat(s, ")"); Debug.Log(s); } } }