9. メソッド
9.1 メソッド
メソッド名は自分の好きな名前をつけてもよいですが、一部つけられない名前もあります。
以下のスクリプトはaaa()メソッドはどこからも呼ばれていません。
void Start(){
}
void Update(){
}
void aaa(){
Debug.Log("aaaが呼ばれた");
}
メソッドの呼び出し
Startメソッドで呼ぶようにします。
処理の流れは、Unity側からStartメソッドが呼ばれてから、Startメソッド内で記述したaaaメソッドが呼ばれます。
void Start(){
aaa();
}
void Update(){
}
void aaa(){
Debug.Log("aaaが呼ばれた");
}
メソッドの処理順
以下の一連の処理の流れは1フレーム内で行われます。
- メソッドが呼び出される(呼び出し元) → 直ちに処理を実行する
- 処理が終わる → 呼び出し元に戻る
void Start(){
Debug.Log("Start1");
aaa();
Debug.Log("Start2");
}
void Update(){
}
void aaa(){
Debug.Log("aaaが呼ばれた");
}
メソッドは何度でも呼べる
メソッドは何度でも呼べます。
void Start(){
aaa();
aaa();
aaa();
}
void Update(){
}
void aaa(){
Debug.Log("aaaが呼ばれた");
}
void Start(){
int b = 0;
aaa();
aaa();
aaa();
Debug.Log(b);
}
void Update(){
}
void aaa(){
int b = 0;
++b;
Debug.Log("aaaが呼ばれた");
}
9.2 引数のあるメソッド
void Start(){
//定義した変数と同じ型のデータを入れます
aaa(1);
}
void Update(){
}
//変数を定義します
//aaa(1)からデータが渡されます
void aaa(int b){ //引数
Debug.Log(b);
}
void Start(){
//型があっていればいろんなデータが送れます。
aaa(1);
aaa(2);
aaa(3);
}
void Update(){
}
void aaa(int b){
Debug.Log(b);
}
変数のスコープに気をつけた引数の扱い方
同じ名前の変数でスコープが被っている場合は、スコープが狭い方が優勢されます。
void Start(){
int b = 0;
aaa(b);
aaa(b);
aaa(b);
Debug.Log(b);
}
void Update(){
}
void aaa(int b){
++b;
}
スコープが狭い方が優先されます。
int b = 0;
void Start(){
aaa(b);
aaa(b);
aaa(b);
Debug.Log(b);
}
void Update(){
}
void aaa(int b){
++b;
}
複数の引数
,で区切ることで複数の引数を定義できます。
void Start(){
//,で区切って引数と同じようにデータをいれる
//複数データを渡せる
aaa(1,2,3);
}
void Update(){
}
void aaa(int a, int b, int c){
Debug.Log(a + b + c);
}
9.3 返り値(戻り値)のあるメソッド
値を返すメソッドを作成します。
void Start(){
//返ってきたデータを代入
int b = aaa(1,2,3);
Debug.Log(b);
}
void Update(){
}
//返すデータの型
int aaa(int a, int b, int c){
//returnは定義した型と同じ型のデータを返す
return a + b + c;
}
returnについて
return以下の命令は処理されません。
int aaa(int a, int b, int c){
return a + b + c;
Debug.Log("aaa");
}
9.4 メソッド内にあるデータを返した場合
メソッドで値を返していますが、スコープ内の変数が優先されるのと、返した値を受け取っていないので変数bは0になります。
void Start(){
int b = 0;
aaa(b);
aaa(b);
aaa(b);
Debug.Log(b);
}
void Update(){
}
void aaa(int b){
return ++b;
}
メソッドから値を受けるには変数bに代入します。
void Start(){
int b = 0;
b = aaa(b);
b = aaa(b);
b = aaa(b);
Debug.Log(b);
}
void Update(){
}
void aaa(int b){
return ++b;
}