テキストを連続した Unicode 文字として表現します。
Unity は文字列として .Net System.String クラスを使用します。詳細については Microsoft MSDN
ドキュメントの Strings
を参照して下さい。
注意: C# で string は System.String のエイリアスです。つまり
string または String のどちらもコードで使用できます。( using System
をコード冒頭で追加することが前提。)
注意: Javascript で string は String により表現されるため、
これを Unity スクリプトコードで使用すべきです。
String クラスの基本的な使用方法を次に示します。
// Javascript
#pragma strict
function Start () {
var s : String = "hello";
Debug.Log(s); // prints hello
s = String.Format("{0} {1}", s, "world");
Debug.Log(s); // prints hello world
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 helloworld
//Debug.Log(s.CharAt(1)); // CharAt not supported, produces compiler error
// instead use array syntax below
Debug.Log(s[1]); // prints e
var c : char = 'x'[0]; // slight odd JS way of specifying a char
// 'x' is a string and [0] means first character
Debug.Log(s.IndexOf(c)); // prints -1 (s does not contain an x)
var i : int = 42;
s = i.ToString();
Debug.Log(s); // prints 42
s = "-43";
i = int.Parse(s);
Debug.Log(i); // prints -43
var f : float = 3.14159265358979f;
s = f.ToString();
Debug.Log(s); // prints 3.141593 (which is an approximation)
s = "-7.14159265358979";
f = float.Parse(s);
Debug.Log(f); // prints -7.141593 (which is an approximation)
}
このサンプルで String クラスについて明らかにしたうえ、含まれるメソッドを確認する 方法を示します。
// Javascript
#pragma strict
import System;
import System.Reflection;
function Start () {
var t : Type = 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.
for (var mi : MethodInfo in t.GetMethods()) {
var s : System.String = System.String.Format("{0} {1} (", mi.ReturnType, mi.Name);
var pars : ParameterInfo[] = mi.GetParameters();
for (var j : int = 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);
}
}