他のクラスのメソッドを使う

Unity 知恵袋

他のクラスのメソッドを使う方法。

functions.cs:共通の関数を宣言するスクリプト

MainScene.cs:メインのシーンを制御するスクリプト

ファイル毎に同じような関数を作ると、面倒な時やコスト面保守性も考えると、ひとまとめにし、

そこから参照したい場合があります。

下記の例では、[function.cs]に存在する”Functions_Console”を”MainScene.cs”から実行させる例です。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class functions : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }
 
    // Update is called once per frame
    void Update()
    {
        
    }

    //この関数を呼び出したい。
    public void Functions_Console(string str){
      Debug.Log(str);
    }
}

他のメソッドの関数を使用する場合は、

(1)emptyGameobjectを作成します。[今回は、名前をFunctionとします。]

(2)”Function”に”functions.cs”をアタッチしましょう。

(3)そのあと、MainScene.csがアタッチされているオブジェクトに、(1)で作成した”Function”をアタッチします。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class MainScene : MonoBehaviour
{

    public GameObject Function;

    // Start is called before the first frame update
    void Start()
    {
        Function.GetComponent<function>().Functions_Console("assign");   //Functions_Consoleを実行
    }
 
    // Update is called once per frame
    void Update()
    {
        
    }

}

上記のコードを説明いたします。

Functionを宣言し、GetComponent<スクリプト名>.呼び出したい関数名 によって実現しています。

関連記事

この記事へのコメントはありません。