【忙しい人のためのUnity入門講座】 引数や返り値を含む関数(メソッド)の作り方
はじめに
この記事ではUnityで関数の作成方法と呼び出し方を紹介します。
関数(メソッド)の作り方
メソッドとは、「意味のある処理毎に分解して名前をつけたもの」です。
「public void Method() {処理}」のように使います。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Test : MonoBehaviour
{
// Use this for initialization
void Start()
{
Method();
}
// Update is called once per frame
void Update()
{
}
public void Method()
{
Debug.Log("処理");
}
}
実行結果
処理引数ありのメソッドの作り方
引数ありの場合は「public void Method ( 型名 変数名) {}」のように利用します。
後から数字を代入したいときに利用します。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Test : MonoBehaviour
{
// Use this for initialization
void Start()
{
Method(100);
}
// Update is called once per frame
void Update()
{
}
public void Method(int i)
{
Debug.Log("i:" + i);
}
}
実行結果
i:100返り値のあるメソッドの作り方
返り値とは、例えば以下のコードのように利用します。
「public int Method() {return a;}」で、int 型の値を返し、Method() = a のように、メソッドが変数のような働きをします。
public string Hoge() なら string 型を返す必要があります。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Test : MonoBehaviour
{
// Use this for initialization
void Start()
{
Debug.Log("a:" + Method());
}
// Update is called once per frame
void Update()
{
}
public int Method()
{
int a = 100;
return a;
}
}
実行結果
a:100返り値、引数ありのメソッドの作り方
返り値、引数ありの場合「public int Method (int i){return a;}」のように使います。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Test : MonoBehaviour
{
// Use this for initialization
void Start()
{
Debug.Log("a:" + Method(100));
}
// Update is called once per frame
void Update()
{
}
public int Method(int a)
{
return a;
}
}
実行結果
a:100